JsonHelp.cs
using System.IO; using System.Text; using System.Runtime.Serialization.Json; namespace WebApp { public class JsonHelp { //序列化 //对象转化为Json字符串 public static string Serialize(object objectToSerialize) { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType()); serializer.WriteObject(ms, objectToSerialize); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { return reader.ReadToEnd(); } } } /// <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; } } }