前言:由於近期在與ERP對接接口中,需要使用Json傳遞數據,故在網上查詢和自己做了實例測試,得出以下生成與解析Json字符串的總結:
一 . 原始方式:按照JSON字符串格式自己來生成與解析。
二 . 通用方式:使用開源的類庫 Newtonsoft.Json(使用該方法首先需在“管理NuGet程序包“中下載:“Newtonsoft.Json”:程序包)
1>實現對象的序列化和反序列化
//首先新建對象Model
class Class{ public int id { get; set; } public string name { get; set; } }
class Student{public int id { get; set; } public string name { get; set; } public Class Class { get; set; } }
* 序列化 (使用方法:public static string SerializeObject([NullableAttribute(2)] object value);)
Student stu = new Student();//新建對象實例 stu.id = 1; stu.name = "張三"; stu.Class = new Class() { id = 1, name = "終極一班" }; string json1 = JsonConvert.SerializeObject(stu);//將對象序列化,生成Json字符串 Console.WriteLine(json1);
結果:json1 : {"id":1,"name":"張三","Class":{"id":1,"name":"終極一班"}}
*反序列化 (使用方法:public static T DeserializeObject<[NullableAttribute(2)]T>(string value);)
Student stu2 = JsonConvert.DeserializeObject<Student>(json1);
2>匿名對象的序列化,反序列化
//匿名對象的解析, //匿名獨享的類型 obj.GetType().Name: "<>f__AnonymousType0`2" var obj = new { ID = 2, Name = "李四" }; string json3 = JsonConvert.SerializeObject(obj);//-------------------------------------------------------------------------------------------------------------序列化 Console.WriteLine(json3); object obj2 = JsonConvert.DeserializeAnonymousType(json3, obj); object id = obj2.GetType().GetProperty("ID").GetValue(obj2);//.GetType()--獲取匿名類型 .GetProperty()--獲取匿名類型參數 .GetValue()--獲取參數值 Console.WriteLine(obj2.GetType().GetProperty("ID").GetValue(obj2)); object obj3 = JsonConvert.DeserializeAnonymousType(json3, new { ID = default(int), Name = default(string) });//------------------------------------------------反序列化
//匿名對象解析,可以傳入現有類型,進行轉換 Student stu3 = new Student(); stu3 = JsonConvert.DeserializeAnonymousType(json3, new Student());//匿名對象轉換成現有對象 Console.WriteLine(stu3.name);
JSON生成實體類工具:點擊>>
三 . 內置方式:使用.NET Framework 3.5/4.0中提供的System.Web.Script.Serialization命名空間下的JavaScriptSerializer類進行對象的序列化與反序列化,很直接。
Project p1 = new Project() { Input = "stone", Output = "gold" }; JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonStr = serializer.Serialize(p1); //序列化:對象=>JSON字符串 Response.Write(jsonStr); Project p2 = serializer.Deserialize<Project>(jsonStr); //反序列化:JSON字符串=>對象 Response.Write(p1.Input + "=>" + p2.Output);
注意:如果使用的是VS2010,則要求當前的工程的 Target Framework要改成.Net Framework 4,不能使用Client Profile。當然這個System.Web.Extensions.dll主要是Web使用的,直接在Console工程中用感覺有點浪費資源。
此外,從最后一句也可以看到,序列化與反序列化是深拷貝的一種典型的實現方式。
備注:
json格式字符串轉換為實體類,大括號{}表示對象,[]數組表示列表。