Custom JsonConverter from NewtonSoft.Json deserializes to DateTime, not working

I am trying to deserialize Unix timestampbefore DateTime. In my case, I need to do a lot more checks before I can set the DateTime property from a timestamp. If I use DateTimeout Newtonsoft.Json, it will deserialize it before UTCtime, and I need to deserialize it in a specific time zone

The problem is that I cannot get the correct time. It seems that my line in is longnot working. If I can get the longunix timestamp , I can get the rest of the logical work.

I have a class named Alert

class Alert
{
    // Some properties

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

    // Some more properties
}

class UnixTimestampJsonConverteris equal

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;
    }
}

TimeUtils.GetCustomDateTime (instance) unixtimestamp DateTime .

PCL Profile 78, System.TimeZoneInfo, PCL NodaTime .


, - , Github - MBTA Sharp

+4
1

, , , serializer.Deserialize. , :

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; } 
    }
}

: https://dotnetfiddle.net/Fa8Zis

+6

All Articles