[SOLVED] Deserialize JSON date value including a time zone


This Content is from Stack Overflow. Question asked by Baxter

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


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!


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)

This Question was asked in StackOverflow by Baxter and Answered by WisdomSeeker It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?