using System.IO; using System.Runtime.Serialization.Json; using System.Text; namespace WebTest.Controllers { public class JsonConvert { /// <summary> /// 将对象转换为json /// </summary> /// <typeparam name="T"><peparam> /// <param name="t"></param> /// <returns></returns> 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> /// <typeparam name="T">对象<peparam> /// <param name="json">json数组</param> /// <returns></returns> public T Deserialize<T>(string json) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); T obj = (T)ser.ReadObject(ms); ms.Close(); return obj; } } }