建议直接用json.net: http://www.cnblogs.com/xwgli/archive/2013/08/30/3290964.html
添加引用:System.Runtime.Serialization
JsonHelper.cs代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Json; namespace Common { /// <summary> /// JSON序列化和反序列化辅助类 /// </summary> public class JsonHelper { /// <summary> /// JSON序列化 /// </summary> public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// <summary> /// JSON反序列化 /// </summary> public static T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } } }
参考文献:
http://www.cnblogs.com/zhaozhan/archive/2011/01/09/1931340.html
http://www.cnblogs.com/coderzh/archive/2008/11/25/1340862.html
时间: 2024-10-25 07:53:55