目前在项目中经常使用Newtonsoft.Json,因项目需要对其中的特定数据类型序列化有特殊要求,特地学习了下如何对Newtonsoft.Json的序列化进行自定义扩展开发。
1、对DateTime类型,序列化输出为时间戳;
2、对string类型,序列化输出为Unicode字符。
针对需求1的序列化扩展特性代码:
/// <summary> /// Newtonsoft.Json序列化扩展特性 /// <para>DateTime序列化(输出为时间戳)</para> /// </summary> public class TimestampConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(DateTime); } public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer) { return ConvertIntDateTime((int)existingValue); } public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer) { writer.WriteValue(ConvertDateTimeInt((DateTime)value)); } public static DateTime ConvertIntDateTime(int aSeconds) { return new DateTime(1970,1,1).AddSeconds(aSeconds); } public static int ConvertDateTimeInt(DateTime aDT) { return (int)(aDT - new DateTime(1970,1)).TotalSeconds; } }
针对需求2的序列化扩展特性代码:
/// <summary> /// Newtonsoft.Json序列化扩展特性 /// <para>String Unicode 序列化(输出为Unicode编码字符)</para> /// </summary> public class UnicodeConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(string); } public override object ReadJson(JsonReader reader,JsonSerializer serializer) { return existingValue; } public override void WriteJson(JsonWriter writer,JsonSerializer serializer) { writer.WriteValue(ToUnicode(value.ToString())); } public static string ToUnicode(string str) { byte[] bts = Encoding.Unicode.GetBytes(str); string r = ""; for (int i = 0; i < bts.Length; i += 2) { r += "\\u" + bts[i + 1].ToString("X").PadLeft(2,'0') + bts[i].ToString("X").PadLeft(2,'0'); } return r; } }
使用方式:
public class Base { [JsonConverter(typeof(TimestampConverter))] public DateTime ExpiresTime { get;set; } [JsonConverter(typeof(UnicodeConverter))] public string Name { get;set; } }原文链接:https://www.f2er.com/json/289416.html