. NET custom JSON serialization time format

Source: Internet
Author: User

. NET custom JSON serialization time format

Intro

and the JAVA project group docking, their interface to return the data is a JSON string, the time there is a Unix timestamp, there are some string type, some or empty, the default serialization rules can not be deserialized into time, so the custom of a JSON time converter to support the nullable time type , string, long (Unix timestamp milliseconds)

Show me the Code
 Public classCustomdatetimeconverter:javascriptdatetimeconverter {/// <summary>        ///overriding 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, which is being converted.</param>        /// <param name= "Serializer" >The calling serializer.</param>        /// <returns></returns>         Public Override ObjectReadjson (Jsonreader Reader, Type ObjectType,ObjectExistingvalue, Jsonserializer Serializer) {            if(Reader. Value = =NULL)//compatible with nullable time types            {                return NULL; }            Else            {                if(Reader. Tokentype = =jsontoken.date) {returnReader.                Value; }                Else if(Reader. Tokentype = =jsontoken.string) {DateTime dt=DateTime.Parse (reader.                    Value.tostring ()); returnDT; }                Else                {                    return NewDateTime (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 way to achieve this, please

Please feel free to contact me [email protected]

. NET custom JSON serialization time format

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.