json.net使用说明三

匿名类型序列化

首先定义一个匿名对对象,并序列化成Json,用于测试。 如何将这个Josn字符串转换为JSON对象呢?如果先创建一个类的话,那就太累了。
复制代码
var o = new
{
   a = 1,
   b = "Hello, World!",
   c = new[] { 1, 2, 3 },
   d = new Dictionary<string, int> { { "x", 1 }, { "y", 2 } }
};

var json = JsonConvert.SerializeObject(o);
复制代码
 

第一种做法(匿名类):

var anonymous = new { a = 0, b = String.Empty, c = new int[0], d = new Dictionary<string, int>() };
var o2 = JsonConvert.DeserializeAnonymousType(json, anonymous);

Console.WriteLine(o2.b);
Console.WriteLine(o2.c[1]);

 

 

第二种做法(匿名类):

 

var o3 = JsonConvert.DeserializeAnonymousType(json, new { c = new int[0], d = new Dictionary<string, int>() });
Console.WriteLine(o3.d["y"]);

    DeserializeAnonymousType 只是借助这个匿名对象参数(anonymous) 反射类型而已,也就是说它和反序列化结果并非同一个对象。正如 o3 那样,我们也可以只提取局部信息。

 

第三种做法(索引器):

 

     实际上,我们也可以直接反序列化为 JObject,然后通过索引器直接访问。JObject、JProperty 等都继承自 JToken,它重载了基元类型转换操作符,我们可以直接得到实际结果。

var o2 = JsonConvert.DeserializeObject(json) as JObject;

Console.WriteLine((int)o2["a"]);
Console.WriteLine((string)o2["b"]);
Console.WriteLine(o2["c"].Values().Count());
Console.WriteLine((int)o2["d"]["y"]);
posted @ 2018-07-24 22:09  辣根弟弟  阅读(195)  评论(0编辑  收藏  举报