Search code examples
c#jsondatetimesystem.text.json

How specify default a timezone for dates with a JsonSerializer?


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


Solution

  • 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.