JSON.NET自定義Json序列化時間格式
Intro
有個項目要和 JAVA 項目組對接,要調用他們的接口圃泡,他們的接口返回的數(shù)據(jù)是一個 json,里面的時間有的是Unix時間戳愿险,有的是string類型颇蜡,有的還是空,默認序列化規(guī)則沒辦法反序列化為時間辆亏,
所以自定義了一個 Json 時間轉換器风秤,支持可空時間類型、string扮叨、long(Unix時間戳毫秒)缤弦。無力吐槽。彻磁。碍沐。
Show me the code
這里實現(xiàn)了一個自定義的 JsonConverter 惦费,自定義反序列化操作
public class CustomDateTimeConverter : JavaScriptDateTimeConverter
{
/// <summary>
/// 重寫JavaScriptDateTimeConverter ReadJson 方法
/// </summary>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns></returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null) //兼容可空時間類型
{
return null;
}
else
{
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
else if (reader.TokenType == JsonToken.String)
{
DateTime dt = DateTime.Parse(reader.Value.ToString());
return dt;
}
else
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(reader.Value)).ToLocalTime();
}
}
}
}
How To Use
使用的時候只需要在反序列化的時候,設置我們自定義的 JsonConverter
(CustomDateTimeConverter
) 就可以了抢韭,代碼如下所示:
var model = JsonConvert.DeserializeObject<ResponseModel>(res,new CustomDateTimeConverter());
End
如果你有更好的實現(xiàn)方法薪贫,歡迎提出
歡迎隨時聯(lián)系我 weihanli@outlook.com