首先先添加.NET引用
System.Runtime.Serialization.dll
System.ServiceModel.Web.dll
然后CS文件添加USing 引用
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
把JSON序列化成对象
/// <summary>
/// 反序列化JSON
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="jsonString">JSON字符串</param>
/// <returns></returns>
public static T JsonDeserialize<T>(string strJson)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
T objT = (T)ser.ReadObject(ms);
ms.Close();
return objT;
}
/// 反序列化JSON
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="jsonString">JSON字符串</param>
/// <returns></returns>
public static T JsonDeserialize<T>(string strJson)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
T objT = (T)ser.ReadObject(ms);
ms.Close();
return objT;
}
把对象序列化成JSON
/// <summary>
/// 序列化JSON
/// </summary>
/// <typeparam name="T">序列化对象类型</typeparam>
/// <param name="objT">序列化对象</param>
/// <returns></returns>
public static string JsonSerializer<T>(T objT)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, objT);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// 序列化JSON
/// </summary>
/// <typeparam name="T">序列化对象类型</typeparam>
/// <param name="objT">序列化对象</param>
/// <returns></returns>
public static string JsonSerializer<T>(T objT)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, objT);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}