using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Falit.Run.Utils
{
///
/// Json帮助类
///
public static class JsonHandleHelper
{
///
/// 将对象序列化为JSON格式
///
/// 对象
/// json字符串
public static string SerializeObject(object o)
{
string json = JsonConvert.SerializeObject(o);
return json;
}
///
/// 解析JSON字符串生成对象实体
///
/// 对象类型
/// json字符串(eg.{"ID":"112","Name":"石子儿"})
/// 对象实体
public static T DeserializeJsonToObject(string json) where T : class
{
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;
}
///
/// 解析JSON字符串生成对象实体 第二种方法
///
///
///
///
public static T DeJsonSerializer(string json)
{
if (json == null)
{
return default(T);
}
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
object obj = ser.ReadObject(ms);
ms.Close();
if (obj == null)
{
throw new NotImplementedException("序列化实体为NULL,json:" + json);
}
return (T)obj;
}
}
///
/// 解析JSON数组生成对象实体集合
///
/// 对象类型
/// json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])
/// 对象实体集合
public static List DeserializeJsonToList(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List));
List list = o as List;
return list;
}
///
/// 反序列化JSON到给定的匿名对象.
///
/// 匿名对象类型
/// json字符串
/// 匿名对象
/// 匿名对象
public static T DeserializeAnonymousType(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
}