- public static class JsonSerializerHelper
- {
- /// <summary>
- /// 向String对象添加一个扩展方法
- /// </summary>
- /// <typeparam name="T">期望的类型</typeparam>
- /// <param name="json">Json字符数据</param>
- /// <returns>预期的对象图</returns>
- public static T JsonDeserialize<T>(this string json)
- {
- //基于字节数组初始化MemroyStream
- using (MemoryStream mstream =
- new MemoryStream(Encoding.Unicode.GetBytes(json)))
- {
- //实例化DataContracctJsonSerializer对象
- DataContractJsonSerializer serializer =
- new DataContractJsonSerializer(typeof(T));
- //从流中读取对象类型,强制转换为指定的对象
- return (T)serializer.ReadObject(mstream);
- }
- }
- /// <summary>
- /// 序列化对象到Json字符串
- /// </summary>
- /// <param name="obj">要序列化的对象</param>
- /// <returns>返回序列化后的字符串</returns>
- public static string JsonSerialize(this object obj)
- {
- //实例化MemoryStream以预备序列化
- using (MemoryStream mstream = new MemoryStream())
- {
- DataContractJsonSerializer serializer =
- new DataContractJsonSerializer(obj.GetType()); //实例化序列化类
- serializer.WriteObject(mstream, obj); //将对象写入到流中
- mstream.Position = 0; //重新定位
- //使用StreamReader,从流中读取字符串
- using (StreamReader reader = new StreamReader(mstream))
- {
- return reader.ReadToEnd(); //返回序列化字符串
- }
- }
- }
- }
- https://github.com/JamesNK/Newtonsoft.Json