. NET custom Json serialization time format, json serialization

Source: Internet
Author: User

. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.