Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库(下载地址http://json.codeplex.com/)。
下面是Json序列化和反序列化的简单封装:
///
/// Json帮助类
/// public class JsonHelper { /// /// 将对象序列化为JSON格式 /// /// 对象 /// json字符串 public static string SerializeObject(object o) { string json = JsonConvert.SerializeObject(o); return json; } /// /// 解析JSON字符串生成对象实体 /// /// 对象类型 /// json字符串(eg.{"ID":"112","Name":"石子儿"}) /// 对象实体 public static T DeserializeJsonToObject(string json) where T : class { JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T)); T t = o as T; return t; } /// /// 解析JSON数组生成对象实体集合 /// /// 对象类型 /// json数组字符串(eg.[{"ID":"112","Name":"石子儿"}]) /// 对象实体集合 public static List DeserializeJsonToList(string json) where T : class { JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List)); List list = o as List; return list; } /// /// 反序列化JSON到给定的匿名对象. /// /// 匿名对象类型 /// json字符串 /// 匿名对象 /// 匿名对象 public static T DeserializeAnonymousType(string json, T anonymousTypeObject) { T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); return t; } }
为进一步理解Newtonsoft,写了一些测试的例子:
///
/// Json测试
/// public class JsonTest : IRun { public void Run() { Student sdudent = new Student(); sdudent.ID = 1; sdudent.Name = "陈晨"; sdudent.NickName = "石子儿"; sdudent.Class = new Class() { Name = "CS0216", ID = 0216 }; //实体序列化和反序列化 string json1 = JsonHelper.SerializeObject(sdudent); //json1 : {"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}} Student sdudent1 = JsonHelper.DeserializeJsonToObject(json1); //实体集合序列化和反序列化 List sdudentList = new List() { sdudent, sdudent1 }; string json2 = JsonHelper.SerializeObject(sdudentList); //json: [{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}},{"ID":1,"Name":"陈晨","NickName":"石子儿","Class":{"ID":216,"Name":"CS0216"}}] List sdudentList2 = JsonHelper.DeserializeJsonToList(json2); //DataTable序列化和反序列化 DataTable dt = new DataTable(); dt.TableName = "Student"; dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Name"); dt.Columns.Add("NickName"); DataRow dr = dt.NewRow(); dr["ID"] = 112; dr["Name"] = "战三"; dr["NickName"] = "小三"; dt.Rows.Add(dr); string json3 = JsonHelper.SerializeObject(dt); //json3 : [{"ID":112,"Name":"战三","NickName":"小三"}] DataTable sdudentDt3 = JsonHelper.DeserializeJsonToObject(json3); List sdudentList3 = JsonHelper.DeserializeJsonToList(json3); //验证对象和数组 Student sdudent4 = JsonHelper.DeserializeJsonToObject("{\"ID\":\"112\",\"Name\":\"石子儿\"}"); List sdudentList4 = JsonHelper.DeserializeJsonToList("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]"); //匿名对象解析 var tempEntity = new { ID = 0, Name = string.Empty }; string json5 = JsonHelper.SerializeObject(tempEntity); //json5 : {"ID":0,"Name":""} tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity); var tempStudent = new Student(); tempStudent = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempStudent); Console.Read(); } } /// /// 学生信息实体 /// public class Student { public int ID { get; set; } public string Name { get; set; } public string NickName { get; set; } public Class Class { get; set; } } /// /// 学生班级实体 /// public class Class { public int ID { get; set; } public string Name { get; set; } }
使用Json帮助类时,有两点需要注意下:
1. 通常使用调用实体序列化SerializeObject()和反序列化DeserializeJsonToObject()两个方法就可以了。但有些情况下我们解析json字符串时,可能没有对应的实体类型(或者说不想添加对应的实体类),这时候可以用匿名对象解析方法DeserializeAnonymousType(),方便快捷,对应代码如下:
//匿名对象解析
var tempEntity = new { ID = 0, Name = string.Empty }; string json5 = JsonHelper.SerializeObject(tempEntity); //json5 : {"ID":0,"Name":""} tempEntity = JsonHelper.DeserializeAnonymousType("{\"ID\":\"112\",\"Name\":\"石子儿\"}", tempEntity); Console.WriteLine(tempEntity.ID + ":" + tempEntity.Name);
2. Json的两种结构数组和对象解析时略有不同。Json对象一般转换成实体,Json数组一般转换成实体集合。代码如下:
//验证对象和数组
Student sdudent4 = JsonHelper.DeserializeJsonToObject("{\"ID\":\"112\",\"Name\":\"石子儿\"}"); List sdudentList4 = JsonHelper.DeserializeJsonToList("[{\"ID\":\"112\",\"Name\":\"石子儿\"}]");
简单解释下Json对象和数组的含义:
对象是以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间运用 “,”(逗号)分隔。名称用引号括起来;值如果是字符串则必须用括号,数值型则不须要。例如:{"ID":"112","Name":"石子儿"}。
数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间运用 “,”(逗号)分隔。例如:[{"ID":"112","Name":"石子儿"},{"ID":"113","Name":"陈晨"}]。