C#对象和Json互转帮助类

using System.Runtime.Serialization.Json;

        #region JSON和C#对象互转
/// < summary >
/// Json转换成对象
/// </ summary >
/// < typeparam name = "T" ></ typeparam >
/// < param name = "jsonText" ></ param >
/// < returns ></ returns >
public static T JsonToObject<T>( string jsonText)
{
DataContractJsonSerializer s = new DataContractJsonSerializer( typeof( T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
T obj = ( T)s.ReadObject(ms);
ms.Dispose();
return obj;
}
/// < summary >
/// 对象转换成JSON
/// </ summary >
/// < typeparam name = "T" ></ typeparam >
/// < param name = "obj" ></ param >
/// < returns ></ returns >
public static string ObjectToJSON<T>( T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T));
string result = string.Empty;
using ( MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;

using ( StreamReader read = new StreamReader(ms))
{
result = read.ReadToEnd();
}
}
return result;
}
#endregion

猜你喜欢

转载自blog.csdn.net/qq_28017061/article/details/80829668