我們用到的類庫為:Newtonsoft.Json,通過VS工具中NuGet程序包可以下載。
一:對象轉json-序列化
public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } //第一種:單一實體類 Student s = new Student(); s.Age = 18; s.ID = 1; s.Name = "張三"; string json = Newtonsoft.Json.JavaScriptConvert.SerializeObject(s);//序列化對象(對象轉json) //第二種:List<T>泛型 和上邊方法相同 List<Student> list = new List<Student>(); for (int i = 1; i < 5; i++) { Student stu = new Student(); stu.Age = i + 12; stu.ID = i; stu.Name = "No."+i.ToString(); list.Add(stu); } json = Newtonsoft.Json.JavaScriptConvert.SerializeObject(list);
二:json轉對象 - 反序列化
//json只有一條數據 JavaScriptObject obj = (JavaScriptObject)JavaScriptConvert.DeserializeObject(json); string Name = obj["Name"].ToString();//取出某一字段 Response.Write(Name); //json只有一條數據 Student ms = (Student)JavaScriptConvert.DeserializeObject(JavaScriptConvert.SerializeObject(obj), typeof(Student));//json轉對象 Response.Write(ms.Name); //json有多條數據 JavaScriptArray javascript = (JavaScriptArray)JavaScriptConvert.DeserializeObject(json); List<Student> slist = new List<Student>(); for (int i = 0; i < javascript.Count; i++) { JavaScriptObject temp = (JavaScriptObject)javascript[i]; Student model = (Student)JavaScriptConvert.DeserializeObject(JavaScriptConvert.SerializeObject(temp), typeof(Student)); slist.Add(model); }
//4.0方法
List<Student> slist = JsonConvert.DeserializeObject<List<Student>>(json);
Response.Write(slist[0].Name);