0

I am attempting to deserialize the json data coming back from an API into a C# object:

httpClient.GetFromJsonAsync<List<Email>>(URL)

public class Email
{
    public DateTime activityDate { get; set; }
}

However, the json date data looks like this:

"activityDate": "2022-07-28T11:04:17.000-0400",

Which results in the following error: The JSON value could not be converted to System.DateTime. The JSON value is not in a supported DateTime format.

I am guessing this is because of the -0400 time zone value on the end of the JSON date. Any ideas on what I might do to nudge this non-standard date format into a C# DateTime during deserialization?

Thanks for any help with this!

Baxter
  • 5,633
  • 24
  • 69
  • 105
  • Assuming you are using .Net WebAPI you can try and update the SerializerSettings, refer to this post https://stackoverflow.com/questions/11553760/why-does-json-net-deserializeobject-change-the-timezone-to-local-time – Orenico Sep 18 '22 at 16:00
  • What parser are you using? – Serge Sep 18 '22 at 17:39
  • I am using System.Net.Http.Json in a .NET 6 console application. – Baxter Sep 19 '22 at 17:38

1 Answers1

0

Use JsonSerializerOptions to achieve this. Please try this.

JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeConverterUsingDateTimeParse());

httpClient.GetFromJsonAsync<List<Email>>(URL, options);

And add this class to specify the overrides

public class DateTimeConverterUsingDateTimeParse : System.Text.Json.Serialization.JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.Parse(reader.GetString() ?? string.Empty);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}
WisdomSeeker
  • 854
  • 6
  • 8