《转》c# 解析JSON的几种办法

文章来自:http://www.cnblogs.com/ambar/archive/2010/07/13/parse-json-via-csharp.html

最近项目经常用到c# 解析JSON,在网上找了好多资料。这篇文章作者描叙得非常详细。故转载下来。

 对比

.NET下几种常见的解析JSON方法
主要类命名空间限制内建LINQ支持
DataContractJsonSerializer System.Runtime.Serialization.Json 通用
JavaScriptSerializer System.Web.Script.Serialization 只能在Web环境使用
JsonArrayJsonObjectJsonValue System.Json 只能在Silverlight中使用
JsonConvertJArrayJObjectJValueJProperty Newtonsoft.Json 通用

 

 

准备数据

实体类:

 1  [DataContract]
 2     public class Person
 3     {
 4         [DataMember(Order = 0, IsRequired = true)]
 5         public string Name { get; set; }
 6 
 7         [DataMember(Order = 1)]
 8         public int Age { get; set; }
 9 
10         [DataMember(Order = 2)]
11         public bool Alive { get; set; }
12 
13         [DataMember(Order = 3)]
14         public string[] FavoriteFilms { get; set; }
15 
16         [DataMember(Order = 4)]
17         public Person Child { get; set; }
18     }

 

 定义:

 1 Action<object> log = o => Console.WriteLine(o);
 2 Func<int, int, int> add = (x, y) => x + y;
 3 
 4 var p1 = new Person {
 5     Age = 12,
 6     Alive = true,
 7     Name = "lj",
 8     FavoriteFilms = new[] { "Up", "Avatar" }
 9 };
10 var p2 = new Person() { Age = 28, Name = "cy", Child = p1 };

使用DataContractJsonSerializer

帮助类:

 1 // using System.Runtime.Serialization.Json;
 2     
 3     /// <summary>
 4     /// 解析JSON,仿Javascript风格
 5     /// </summary>
 6     public static class JSON
 7     {
 8 
 9         public static T parse<T>(string jsonString)
10         {
11             using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
12             {
13                 return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
14             }
15         }
16 
17         public static string stringify(object jsonObject)
18         {
19             using (var ms = new MemoryStream())
20             {
21                 new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
22                 return Encoding.UTF8.GetString(ms.ToArray());
23             }
24         }
25     }

用法:

1   // 序列化
2     var jsonString = JSON.stringify(new[] { p1, p2 });
3     log(jsonString == JSON.stringify(new List<Person>() { p1, p2 }));   //true
4     log(jsonString);
5     // 反序列化,泛型集合
6     JSON.parse<List<Person>>(jsonString);
7     // 数组转换            
8     JSON.parse<Person[]>(jsonString);

 

 输出:

1 [{"Name":"lj","Age":12,"Alive":true,"FavoriteFilms":["Up","Avatar"],"Child":null
2 },{"Name":"cy","Age":28,"Alive":false,"FavoriteFilms":null,"Child":{"Name":"lj",
3 "Age":12,"Alive":true,"FavoriteFilms":["Up","Avatar"],"Child":null}}]

使用JavaScriptSerializer

1 // using System.Web.Script.Serialization;
2     
3     var jser    = new JavaScriptSerializer();
4     var json    = jser.Serialize(new List<Person>() { p1, p2 });
5     var persons = jser.Deserialize<List<Person>>(json);

使用Silverlight

 1 / using System.Json
 2     
 3     var css = "{ \"#header\" : {background:\"red\"}, layout : [5,4,1],color:\"cyan\" }";
 4     
 5     var style = JsonObject.Parse(css) as JsonObject;    
 6     
 7     (
 8     from s in style
 9     where s.Key == "color"
10     select (string)s.Value
11     ).First().ToString();    
12     // "cyan"
13     
14     
15     // 更多操作
16     style["layout"][0] = 22;
17     
18     var hd = style["#header"];
19     style["body>div+p"] = hd;
20     style.Remove("#header");
21     
22     var bd = new JsonObject();
23     bd["border"] = "1px solid cyan";
24     style["body>div+p"]["#meta"] = bd;
25     style.ToString();    
26     // {"layout":[22,4,1],"color":"cyan","body>div+p":{"background":"red","#meta":{"border":"1px solid cyan"}}}

使用JSON.NET

1 // using Newtonsoft.Json;
2     
3     var json = JsonConvert.SerializeObject(new[] { p1, p2 });
4     var persons = JsonConvert.DeserializeObject<List<Person>>(json);
5     var ja = JArray.Parse(jsonString);            
6     log(ja);    //注意,格式化过的输出

输出:

 

 

 1 [
 2   {
 3     "Name": "lj",
 4     "Age": 12,
 5     "Alive": true,
 6     "FavoriteFilms": [
 7       "Up",
 8       "Avatar"
 9     ],
10     "Child": null
11   },
12   {
13     "Name": "cy",
14     "Age": 28,
15     "Alive": false,
16     "FavoriteFilms": null,
17     "Child": {
18       "Name": "lj",
19       "Age": 12,
20       "Alive": true,
21       "FavoriteFilms": [
22         "Up",
23         "Avatar"
24       ],
25       "Child": null
26     }
27   }
28 ]

LINQ:

1  var ageCount = ja.Select(j => (int)j["Age"]).Aggregate(add);    
2     var q = from j in ja
3             where !j["Name"].Value<string>().Equals("lj")
4             select (int)j["Age"];
5     
6     log(q.Aggregate(add) == ageCount);  //false

其他:

 1  // 与Linq to XML 相似的嵌套构造函数:
 2     var jo = new JObject(
 3                     new JProperty("age", persons.Select( p => p.Age)),
 4                     new JProperty("funny", true),
 5                     new JProperty("array", new JArray(new[] { 2, 4, 1 }))
 6                     );
 7     log(jo);
 8     
 9     // JObject 操作
10     var css = "{ \"#header\" : {background:\"red\"}, layout : [5,4,1] }";
11     var style = JObject.Parse(css);
12 
13     var bd = new JObject();
14     bd["color"] = "1px solid cyan";
15 
16     style["border"] = bd;
17 
18     var hd = style["#header"];
19     style["body>div+p"] = hd;
20 
21     hd.Parent.Remove();
22 
23     style["layout"][0] = 22;
24     log(style);

输出:

 1    "age": [
 2         12,
 3         28
 4       ],
 5       "funny": true,
 6       "array": [
 7         2,
 8         4,
 9         1
10       ]
11     }
12     {
13       "layout": [
14         22,
15         4,
16         1
17       ],
18       "border": {
19         "color": "1px solid cyan"
20       },
21       "body>div+p": {
22         "background": "red"
23       }
24     }

 

 

 

 

 

posted @ 2014-11-28 09:24  _Dawn  阅读(161)  评论(0)    收藏  举报