. NET custom Json serialization time format, json serialization
. NET custom Json serialization time format
Intro
It is connected to the JAVA project team. The data returned by their interfaces is a json string with Unix timestamp, string type, and null. By default, the serialization rules cannot be deserialized to time, therefore, a custom Json time converter supports null time types, string, and long (Unix timestamp in milliseconds)
Show me the code
Public class CustomDateTimeConverter: javaScriptDateTimeConverter {// <summary> /// rewrite The JavaScriptDateTimeConverter ReadJson method /// </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) // compatible with the null time type {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
var model = JsonConvert.DeserializeObject<ResponseModel>(res,new CustomDateTimeConverter());
End
If you have a better implementation method, you are welcome to propose
Feel free to contact my weihanli@outlook.com