我们用到的类库为: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);