How to deserialize EPOCH using Newtonsoft

Viewed 117

I need to deserialize a JSON using Newtonsoft.Json, one of my values in my JSON has an EPOCH format:

  *"fechaGrabacionODH": {
    "$date": 1634689986082
  },*

Im using this to Deserialize, but it's not working

*var settings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
};*

*Data = JsonConvert.DeserializeObject<Constructores_IdPnODH.Data>(payload_Decryp, settings);**

I'm getting this error:

Unexpected character encountered while parsing value: {. Path 'fechaGrabacionODH', line 1, position 261.

I really appreciate any help. Thanks in advance.

1 Answers

You can use a custom JsonConverter

public class EpochConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var jObject = new JObject();
        jObject["$date"] = new DateTimeOffset((DateTime)value).ToUnixTimeMilliseconds();
        jObject.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);
        var epoch = jObject.GetValue("$date").Value<long>();
        return DateTimeOffset.FromUnixTimeMilliseconds(epoch).UtcDateTime;
    }

    public override bool CanRead => true;

    public override bool CanConvert(Type objectType) => objectType == typeof(DateTime);
}

And then apply it with an attribute

class YourObject{
    [JsonConverter(typeof(EpochConverter))]
    public DateTime fechaGrabacionODH;
}

dotnetfiddle

Related