NewtonSoft.Json custom JsonConverter deserialize t

2019-05-04 14:29发布

I am trying to deserialize a Unix timestamp to a DateTime. In my case, I need to do much more checks before I can set a property to DateTime from a timestamp. If I use DateTime from Newtonsoft.Json it deserializes it to UTC time and I need to deserialize it to a specific timezone

The problem is that I am not able to get the correct time. It seems like my string to long parsing is failing. If I can get the long unix timestamp, I can get the rest of the logic working

I have a class named Alert

class Alert
{
    // Some properties

    [JsonConverter(typeof(UnixTimestampJsonConverter))]
    public DateTime Created { get; set; }

    // Some 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)
            return null;

        if (reader.TokenType == JsonToken.StartObject) {
            long instance = serializer.Deserialize<long> (reader);
            return TimeUtils.GetCustomDateTime (instance);
        }

        return null;
    }
}

Where TimeUtils.GetCustomDateTime (instance) takes the long unixtimestamp and converts it into DateTime object of specific timezone.

I am in a PCL library with Profile 78, so I have limited access to System.TimeZoneInfo and I am using PCL version of NodaTime for other timezone calculations.


In case anyone is interested, this is the project on Github - MBTA Sharp

1条回答
Root(大扎)
2楼-- · 2019-05-04 15:19

I'm pretty sure all you need to do is call serializer.Deserialize. Doing this will advance the reader correctly and you shouldn't need to do anything else:

public class UnixTimestampJsonConverter : JsonConverter
{
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        long ts = serializer.Deserialize<long>(reader);

        return TimeUtils.GetMbtaDateTime(ts);
    }

    public override  bool CanConvert(Type type)
    {
        return typeof(DateTime).IsAssignableFrom(type);
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanRead
    { 
        get { return true; } 
    }
}

Example: https://dotnetfiddle.net/Fa8Zis

查看更多
登录 后发表回答