ASP.NET MVC Json的序列化和反序列化
1.利用js进行序列化成字符串和反序列化
1 var personObj = {name:"Tom",age:16}; 2 3 // 利用JS序列化成字符串 4 var personStr = JSON.stringify(personObj); 5 6 // 利用JS进行反序列化 7 var personObj2 = JSON.parse(personStr);
2.ASP.MVC后台进行序列化和反序列化
(1)创建一个类来组织传来的数据
1 public Class Person 2 { 3 // 属性名称与JSON中的一致 4 public string name{get;set;} 5 public int age{get;set;} 6 }
(2)序列化工具类
1 /// <summary> 2 /// Json帮助类 3 /// </summary> 4 public class JsonHelper 5 { 6 /// <summary> 7 /// 将对象序列化为JSON格式 8 /// </summary> 9 /// <param name="o">对象</param> 10 /// <returns>json字符串</returns> 11 public static string SerializeObject(object o) 12 { 13 string json = JsonConvert.SerializeObject(o); 14 return json; 15 } 16 17 /// <summary> 18 /// 解析JSON字符串生成对象实体 19 /// </summary> 20 /// <typeparam name="T">对象类型</typeparam> 21 /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param> 22 /// <returns>对象实体</returns> 23 public static T DeserializeJsonToObject<T>(string json) where T : class 24 { 25 JsonSerializer serializer = new JsonSerializer(); 26 StringReader sr = new StringReader(json); 27 object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T)); 28 T t = o as T; 29 return t; 30 } 31 32 /// <summary> 33 /// 解析JSON数组生成对象实体集合 34 /// </summary> 35 /// <typeparam name="T">对象类型</typeparam> 36 /// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param> 37 /// <returns>对象实体集合</returns> 38 public static List<T> DeserializeJsonToList<T>(string json) where T : class 39 { 40 JsonSerializer serializer = new JsonSerializer(); 41 StringReader sr = new StringReader(json); 42 object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>)); 43 List<T> list = o as List<T>; 44 return list; 45 } 46 47 /// <summary> 48 /// 反序列化JSON到给定的匿名对象. 49 /// </summary> 50 /// <typeparam name="T">匿名对象类型</typeparam> 51 /// <param name="json">json字符串</param> 52 /// <param name="anonymousTypeObject">匿名对象</param> 53 /// <returns>匿名对象</returns> 54 public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject) 55 { 56 T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); 57 return t; 58 } 59 }
(3)后台序列化
1 List<Person> jsonlist = JsonHelper.DeserializeJsonToList <Person> (jsonObjects);