Monday, 15 July 2013

c# - NewtonSoft.Json custom JsonConverter deserialize to DateTime not working -



c# - NewtonSoft.Json custom JsonConverter deserialize to DateTime not working -

i trying deserialize unix timestamp datetime. in case, need much more checks before can set property datetime timestamp. if utilize datetime newtonsoft.json deserializes utc time , need deserialize specific timezone

the problem not able right time. seems string long parsing failing. if can long unix timestamp, can rest of logic working

i have class named alert

class alert { // properties [jsonconverter(typeof(unixtimestampjsonconverter))] public datetime created { get; set; } // more properties }

the class unixtimestampjsonconverter is

class unixtimestampjsonconverter : jsonconverter { // other override methods public override object readjson (jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { if (reader.tokentype == jsontoken.endobject) homecoming null; if (reader.tokentype == jsontoken.startobject) { long instance = serializer.deserialize<long> (reader); homecoming timeutils.getcustomdatetime (instance); } homecoming null; } }

where timeutils.getcustomdatetime (instance) takes long unixtimestamp , converts datetime object of specific timezone.

i in pcl library profile 78, have limited access system.timezoneinfo , using pcl version of nodatime other timezone calculations.

in case interested, project on github - mbta sharp

i'm pretty sure need phone call serializer.deserialize. doing advance reader correctly , shouldn't need else:

public class unixtimestampjsonconverter : jsonconverter { public override object readjson( jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { long ts = serializer.deserialize<long>(reader); homecoming timeutils.getmbtadatetime(ts); } public override bool canconvert(type type) { homecoming typeof(datetime).isassignablefrom(type); } public override void writejson( jsonwriter writer, object value, jsonserializer serializer) { throw new notimplementedexception(); } public override bool canread { { homecoming true; } } }

example: https://dotnetfiddle.net/fa8zis

c# json datetime timezone json.net

No comments:

Post a Comment