using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Globalization;
namespace Common.Core.Utilities
{
/// <summary>
/// JSON帮助类
/// </summary>
public static class JSONHelper
{
#region 编码
/// <summary>
/// 编码
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="t">要转换的类型数据</param>
/// <returns>json字符串</returns>
public static string Encode<T>(T t)
{
return Encode(t, Formatting.None);
}
#endregion
#region 编码
/// <summary>
/// 编码
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string Encode<T>(T t, Formatting format)
{
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
BigintConverter bigintConverter = new BigintConverter();
//这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
return JsonConvert.SerializeObject(t, format, timeConverter, bigintConverter);
}
#endregion
#region 解码
/// <summary>
/// 解码
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="json">json字符串</param>
/// <returns>类型数据</returns>
public static T Decode<T>(string json)
{
BigintConverter bigintConverter = new BigintConverter();
return (T)JsonConvert.DeserializeObject(json, typeof(T), bigintConverter);
}
#endregion
}
#region Bigint转换成字符串
/// <summary>
/// Bigint类型转换处理
/// </summary>
public class BigintConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(System.Int64)
|| objectType == typeof(System.UInt64);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return 0;
}
else
{
IConvertible convertible = reader.Value as IConvertible;
if (objectType == typeof(System.Int64))
{
return convertible.ToInt64(CultureInfo.InvariantCulture);
}
else if (objectType == typeof(System.UInt64))
{
return convertible.ToUInt64(CultureInfo.InvariantCulture);
}
return 0;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteValue("0");
}
else if (value is Int64 || value is UInt64)
{
writer.WriteValue(value.ToString());
}
else
{
throw new Exception("Expected Bigint value");
}
}
}
#endregion
}