Search code examples
c#jsondatetimesystem.text.json

Deserialise Json Timestamp with System.Text.Json


I am trying to deserialise the following JSON

{"serverTime":1613967667240}

into an object of the following class

public class ApiServerTime
{
    [JsonPropertyName("serverTime")]
    public DateTime ServerTime
    {
        get;
        private set;
    }
}

with the following command:

JsonSerializer.Deserialize<ApiServerTime>(jsonString);

but the resulting object contains the ServerTime == DateTime.MinValue. What am I doing wrong?


Solution

  • You can register custom date formatters for System.Text.Json also. https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support

    public class DateTimeConverterForCustomStandardFormatR : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.UnixEpoch.AddMilliseconds(reader.GetInt64());
        }
    
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            // The "R" standard format will always be 29 bytes.
            Span<byte> utf8Date = new byte[29];
    
            bool result = Utf8Formatter.TryFormat(value, utf8Date, out _, new StandardFormat('R'));
            Debug.Assert(result);
    
            writer.WriteStringValue(utf8Date);
        }
    }
    
    
    string js = "{\"ServerTime\":1613967667240}";
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
    var value = JsonSerializer.Deserialize<ApiServerTime>(js, options);