乀執筆畫卿眉

路漫漫其修远兮,吾将上下而求索。
posts - 57, comments - 10, trackbacks - 0, articles - 0
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

Newtonsoft.Json学习笔记

Posted on 2016-06-29 16:30 乀執筆畫卿眉 阅读(...) 评论(...) 编辑 收藏

Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库(下载地址http://json.codeplex.com/)。

下面是Json序列化和反序列化的简单封装:

 1 /// <summary>
 2     /// Json帮助类
 3     /// </summary>
 4     public class JsonHelper
 5     {
 6         /// <summary>
 7         /// 将对象序列化为JSON格式
 8         /// </summary>
 9         /// <param name="o">对象</param>
10         /// <returns>json字符串</returns>
11         public static string SerializeObject(object o)
12         {
13             string json = JsonConvert.SerializeObject(o);
14             return json;
15         }
16 
17         /// <summary>
18         /// 解析JSON字符串生成对象实体
19         /// </summary>
20         /// <typeparam name="T">对象类型</typeparam>
21         /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
22         /// <returns>对象实体</returns>
23         public static T DeserializeJsonToObject<T>(string json) where T : class
24         {
25             JsonSerializer serializer = new JsonSerializer();
26             StringReader sr = new StringReader(json);
27             object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
28             T t = o as T;
29             return t;
30         }
31 
32         /// <summary>
33         /// 解析JSON数组生成对象实体集合
34         /// </summary>
35         /// <typeparam name="T">对象类型</typeparam>
36         /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
37         /// <returns>对象实体集合</returns>
38         public static List<T> DeserializeJsonToList<T>(string json) where T : class
39         {
40             JsonSerializer serializer = new JsonSerializer();
41             StringReader sr = new StringReader(json);
42             object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
43             List<T> list = o as List<T>;
44             return list;
45         }
46 
47         /// <summary>
48         /// 反序列化JSON到给定的匿名对象.
49         /// </summary>
50         /// <typeparam name="T">匿名对象类型</typeparam>
51         /// <param name="json">json字符串</param>
52         /// <param name="anonymousTypeObject">匿名对象</param>
53         /// <returns>匿名对象</returns>
54         public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
55         {
56             T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
57             return t;
58         }
59     }

 为进一步理解Newtonsoft,写了一些测试的例子:

 1     /// <summary>
 2     /// Json测试
 3     /// </summary>
 4     public class JsonTest : IRun
 5     {
 6         public void Run()
 7         {
 8             Student sdudent = new Student();
 9             sdudent.ID = 1;
10             sdudent.Name = "陈晨";
11             sdudent.NickName = "石子儿";
12             sdudent.Class = new Class() { Name = "CS0216", ID = 0216 };
13 
14             //实体序列化和反序列化
15             string json1 = JsonHelper.SerializeObject(sdudent);
16             //json1 : {"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}}
17             Student sdudent1 = JsonHelper.DeserializeJsonToObject<Student>(json1);
18 
19             //实体集合序列化和反序列化
20             List<Student> sdudentList = new List<Student>() { sdudent, sdudent1 };
21             string json2 = JsonHelper.SerializeObject(sdudentList);
22             //json: [{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}},{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}}]
23             List<Student> sdudentList2 = JsonHelper.DeserializeJsonToList<Student>(json2);
24 
25             //DataTable序列化和反序列化
26             DataTable dt = new DataTable();
27             dt.TableName = "Student";
28             dt.Columns.Add("ID", typeof(int));
29             dt.Columns.Add("Name");
30             dt.Columns.Add("NickName");
31             DataRow dr = dt.NewRow();
32             dr["ID"] = 112;
33             dr["Name"] = "战三";
34             dr["NickName"] = "小三";
35             dt.Rows.Add(dr);
36             string json3 = JsonHelper.SerializeObject(dt);
37             //json3 : [{"ID":112,"Name":"战三","NickName":"小三"}]
38             DataTable sdudentDt3 = JsonHelper.DeserializeJsonToObject<DataTable>(json3);
39             List<Student> sdudentList3 = JsonHelper.DeserializeJsonToList<Student>(json3);
40 
41             //验证对象和数组
42             Student sdudent4 = JsonHelper.DeserializeJsonToObject<Student>("{\"ID\":\"112\",\"Name\":\"石子儿\"}");
43             List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]");
44 
45             //匿名对象解析
46             var tempEntity = new { ID = 0, Name = string.Empty };
47             string json5 = JsonHelper.SerializeObject(tempEntity);
48             //json5 : {"ID":0,"Name":""}
49             tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity);
50             var tempStudent = new Student();
51             tempStudent = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempStudent);
52 
53             Console.Read();
54         }
55 
56     }
57 
58     /// <summary>
59     /// 学生信息实体
60     /// </summary>
61     public class Student
62     {
63         public int ID { get; set; }
64         public string Name { get; set; }
65         public string NickName { get; set; }
66         public Class Class { get; set; }
67     }
68 
69     /// <summary>
70     /// 学生班级实体
71     /// </summary>
72     public class Class
73     {
74         public int ID { get; set; }
75         public string Name { get; set; }
76     }

  使用Json帮助类时,有两点需要注意下:

 1. 通常使用调用实体序列化SerializeObject()和反序列化DeserializeJsonToObject()两个方法就可以了。但有些情况下我们解析json字符串时,可能没有对应的实体类型(或者说不想添加对应的实体类),这时候可以用匿名对象解析方法DeserializeAnonymousType(),方便快捷,对应代码如下:

 

1  //匿名对象解析
2             var tempEntity = new { ID = 0, Name = string.Empty };
3             string json5 = JsonHelper.SerializeObject(tempEntity);
4             //json5 : {"ID":0,"Name":""}
5             tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity);
6             Console.WriteLine(tempEntity.ID + ":" + tempEntity.Name);

 

    2. Json的两种结构数组和对象解析时略有不同。Json对象一般转换成实体,Json数组一般转换成实体集合。代码如下:

 

1 //验证对象和数组
2             Student sdudent4 = JsonHelper.DeserializeJsonToObject<Student>("{\"ID\":\"112\",\"Name\":\"石子儿\"}");
3             List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]");

 

  简单解释下Json对象和数组的含义:

         对象是以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间运用 “,”(逗号)分隔。名称用引号括起来;值如果是字符串则必须用括号,数值型则不须要。例如:{"ID":"112","Name":"石子儿"}。

         数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间运用 “,”(逗号)分隔。例如:[{"ID":"112","Name":"石子儿"},{"ID":"113","Name":"陈晨"}]。

备注: //JavaScriptArray--->  JArray
          //JavaScriptConvert--->JsonConvert  
          //JavaScriptObject--->JObject  

 资源下载:Json90r1