using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class JsonUtils
{
///
/// 反序列化Json字符串生成对象实体
///
/// 对象类型
/// json字符串
/// 对象实体
public static T DeserializeJsonToObject(string jsonStr) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(jsonStr);
object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = obj as T;
return t;
}
catch
{
return null;
}
}
public static string SerializeObject(object obj)
{
return SerializeObjectToString(obj);
}
public static string SerializeObjectToString(object obj, JsonSerializerSettings jsonsetting = null)
{
try
{
string str = "";
if (jsonsetting != null)
str = JsonConvert.SerializeObject(obj, Formatting.None, jsonsetting);
else
str = JsonConvert.SerializeObject(obj, Formatting.None);
return str;
}
catch
{
return null;
}
}
public static T DeserializeJsonToObjectNullable(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
{
return null;
}
}
public static JObject JObjectParse(string json, JsonLoadSettings settings = null)
{
try
{
if (settings == null)
{
JObject obj = JObject.Parse(json);
return obj;
}
else
{
JObject obj = JObject.Parse(json, settings);
return obj;
}
}
catch
{
return null;
}
}
///
/// 解析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;
}
public static List DeserializeJsonToListNullable(string json) where T : class
{
try
{
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;
}
catch
{
return null;
}
}
///
/// 反序列化JSON到给定的匿名对象.
///
/// 匿名对象类型
/// json字符串
/// 匿名对象
/// 匿名对象
public static T DeserializeAnonymousType(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
}