Home > front end >  Deserialize JSON date value including a time zone
Deserialize JSON date value including a time zone

Time:09-19

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!

CodePudding user response:

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());
    }
}

CodePudding user response:

I guess you will need to somehow pass it through DateTime.Parse method.

  • Related