JSON.NET简单序列化
Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库
class BaseTest
{
public int n;
public BaseTest()
{
n = 0;
}
}
static void Main(string[] args)
{
BaseTest bt = new BaseTest();
bt.n = 1;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(bt));
Console.ReadKey();
}
输出
{"n":1}
当类有继承关系的时候…
class BaseTest
{
public int n;
public BaseTest()
{
n = 0;
}
}
class childTest : BaseTest
{
public float f;
public childTest()
: base()
{
f = 1.23f;
}
}
class OtherTest : BaseTest
{
public List<string> strList;
public OtherTest()
: base()
{
strList = new List<string>();
}
}
static void Main(string[] args)
{
List<BaseTest> baselist = new List<BaseTest>();
childTest ct = new childTest();
ct.n = 0;
ct.f = 1.234f;
baselist.Add(ct);
OtherTest ot = new OtherTest();
ot.n = 0;
ot.strList.Add("ot1");
ot.strList.Add("ot2");
baselist.Add(ot);
try
{
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(baselist));
}
catch (Exception e)
{
System.Diagnostics.Debug.Assert(false);
}
Console.ReadKey();
}
输出
[{"f":1.234,"n":0},{"strList":["ot1","ot2"],"n":0}]