using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Newtonsoft.Json;
namespace Commom
{
/// <summary>
/// json帮助
/// </summary>
public static class JsonHelper
{
/// <summary>
/// 转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string ToJson<T>(this T t)
{
string json = JsonConvert.SerializeObject(t);
return json;
}
/// <summary>
/// 转换成json,去掉为null的字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string ToJsonNoNull<T>(this T t)
{
var jsonSetting = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
var json = JsonConvert.SerializeObject(t, Formatting.Indented,jsonSetting);
return json;
}
/// <summary>
/// 转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T ToObject<T>(this string json)
{
T t = JsonConvert.DeserializeObject<T>(json);
return t;
}
/// <summary>
/// 获取Json的Model
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="szJson">Json字符串</param>
/// <returns>实体</returns>
public static T ParseFromJson<T>(String szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}
}
JsonHelper
最新推荐文章于 2024-10-10 07:01:49 发布