/// <summary> /// JSON帮助类 /// </summary> public static class JsonHelper { /// <summary> /// 1.JSON序列化 (将对象转为JSON串) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns>返回JSON串</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;
//方法二:
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反序列化 (将JSON 转为对象) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns>返回T类型的对象</returns> 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; } }
把上述代码方法新建class类中,在项目中直接引用即可