. 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