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获取Dictionary集合 /// </summary> /// <param name="szJson"></param> /// <returns></returns> public static Dictionary<string, string> GetDictionaryFromJson(string szJson) { Dictionary<string, string> list = new Dictionary<string, string>(); System.Web.Script.Serialization.JavaScriptSerializer jsonConvert = new System.Web.Script.Serialization.JavaScriptSerializer(); list = jsonConvert.Deserialize<Dictionary<string, string>>(szJson); return list; } }
Json数据序列化对象,及对象序列化为Json格式
时间: 2024-11-12 02:19:08