json转换工具类
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
namespace JiaWel.Utilities.Json
{
public class JsonConvert
{
/// <summary>
/// 将对象序列化为JSON格式
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="entity">实体</param>
/// <returns>json字符串</returns>
public string EntityToJson<T>(T entity)
{
try
{
return Newtonsoft.Json.JsonConvert.SerializeObject(entity);
}
catch (Exception)
{
ExceptionHelper.WriteException("EntityToJson<T>", "");
throw;
}
}
/// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
/// <returns>对象实体</returns>
public T DeserializeJsonToObject<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
catch (Exception)
{
ExceptionHelper.WriteException("DeserializeJsonToObject<T>", "");
throw;
}
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public List<T> DeserializeJsonToList<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
catch (Exception ex)
{
ExceptionHelper.WriteException("DeserializeJsonToList<T>", "");
throw;
}
}
}
}