How specify default a timezone for dates with a JsonSerializer?

Viewed 691

I am using using System.Text.Json to parse json data. Which contains a date filed without any time associated with it. The parse does work and I get a datetime however the datetime is missing the time zone and the gateway which I am sending this to is rejecting it due to the lack of time zone.

I happen to know that the default time zone for this is infect GMT+2 The issue is how to force it to add the time zone during the parse.

Simple example for your testing pleasure.

I have a simple class with a date in it.

public class Testclass
{

    public DateTime RecordedDate { get; set; }
}

Then I have a Json string

 var json = "{ \"RecordedDate\": \"2017-11-22\"}"; 

Which I then try to parse.

  var response =  JsonSerializer.Deserialize<Testclass>(json);

The parse does work however it does not contain a Timezone is there a way to specify the default timezone?

enter image description here

2 Answers

You can create a DateTimeConvertor and handle the conversion as per your need.

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.SpecifyKind(DateTime.Parse(reader.GetString()), DateTimeKind.Utc);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {          
        writer.WriteStringValue(DateTime.SpecifyKind(value, DateTimeKind.Utc));
    }
}

Use the Convertor during serializing/deserializing.

JsonSerializerOptions options = new JsonSerializerOptions();

options.Converters.Add(new DateTimeConverter());

var response = JsonSerializer.Deserialize<Testclass>(json, options);

var responseJson = JsonSerializer.Serialize(response, options);

The responseJson will have datetime in the desired format.

I think this is by default.

As far as I know, timezone conversion should not be handled while on deserialization (or serialization) process. These topics should be separated in my opinion.

If I were you, I would use TimeZoneInfo.ConvertTime method (or similar ones) after I get DateTime in your process. This of course, might depend the logic of your code.

You might wanna check;

On the other hand, Json.NET supports DateTimeZoneHandling which probably you can use on deserialize as well.

Related