標籤:type code man 添加 wro 進一步 shm 引號 匿名
轉自:http://www.cnblogs.com/freshman0216/p/4161800.html
Newtonsoft.Json,一款.NET中開源的Json序列化和還原序列化類庫(http://json.codeplex.com/)。
下面是Json序列化和還原序列化的簡單封裝:
/// <summary> /// Json協助類 /// </summary> public class JsonHelper { /// <summary> /// 將對象序列化為JSON格式 /// </summary> /// <param name="o">對象</param> /// <returns>json字串</returns> public static string SerializeObject(object o) { string json = JsonConvert.SerializeObject(o); return json; } /// <summary> /// 解析JSON字串產生對象實體 /// </summary> /// <typeparam name="T">物件類型</typeparam> /// <param name="json">json字串(eg.{"ID":"112","Name":"石子兒"})</param> /// <returns>對象實體</returns> public static T DeserializeJsonToObject<T>(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; } /// <summary> /// 解析JSON數組產生對象實體集合 /// </summary> /// <typeparam name="T">物件類型</typeparam> /// <param name="json">json數組字串(eg.[{"ID":"112","Name":"石子兒"}])</param> /// <returns>對象實體集合</returns> public static List<T> DeserializeJsonToList<T>(string json) where T : class { JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>)); List<T> list = o as List<T>; return list; } /// <summary> /// 還原序列化JSON到給定的匿名對象. /// </summary> /// <typeparam name="T">匿名物件類型</typeparam> /// <param name="json">json字串</param> /// <param name="anonymousTypeObject">匿名對象</param> /// <returns>匿名對象</returns> public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject) { T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); return t; } }
為進一步理解Newtonsoft,寫了一些測試的例子:
/// <summary> /// Json測試 /// </summary> 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<Student>(json1); //實體集合序列化和還原序列化 List<Student> sdudentList = new List<Student>() { 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<Student> sdudentList2 = JsonHelper.DeserializeJsonToList<Student>(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<DataTable>(json3); List<Student> sdudentList3 = JsonHelper.DeserializeJsonToList<Student>(json3); //驗證對象和數組 Student sdudent4 = JsonHelper.DeserializeJsonToObject<Student>("{\"ID\":\"112\",\"Name\":\"石子兒\"}"); List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"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(); } } /// <summary> /// 學生資訊實體 /// </summary> public class Student { public int ID { get; set; } public string Name { get; set; } public string NickName { get; set; } public Class Class { get; set; } } /// <summary> /// 學生班級實體 /// </summary> 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<Student>("{\"ID\":\"112\",\"Name\":\"石子兒\"}"); List<Student> sdudentList4 = JsonHelper.DeserializeJsonToList<Student>("[{\"ID\":\"112\",\"Name\":\"石子兒\"}]");
簡單解釋下Json對象和數組的含義:
對象是以“{”(左括弧)開始,“}”(右括弧)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間運用 “,”(逗號)分隔。名稱用引號括起來;值如果是字串則必須用括弧,數值型則不須要。例如:{"ID":"112","Name":"石子兒"}。
數組是值(value)的有序集合。一個數組以“[”(左中括弧)開始,“]”(右中括弧)結束。值之間運用 “,”(逗號)分隔。例如:[{"ID":"112","Name":"石子兒"},{"ID":"113","Name":"陳晨"}]。
Newtonsoft.Json(Json.Net)學習筆記