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( 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 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

你可能感兴趣的:(C#)