.net JsonHelper json帮助类
using Newtonsoft.Json; using System.Runtime.Serialization.Json; using System.Text; public class JsonHelper { /// <summary> /// 生成Json格式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string GetJson<T>(T obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } /// <summary> /// 获取Json的Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } /// <summary> /// 解析JSON数组生成对象实体集合 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="json">json数组字符串(eg.[{"ID":"1","Name":"lttr"}])</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; } }
有错误的请多多指教,共同进步(๑•ᴗ•๑)
By听雨的人
By听雨的人