Deserializing JSON with UTC/Zulu Time String using System.Text.Json

1k views Asked by At

I am having some issues deserializing JSON that has a Zulu formatted time string. I continue to receive an exception that states the string is not a data and time.

I have the following string being returned from and REST service.

{
    ".issued": "2023-03-01T13:26:35.1134406Z",
    ".expires": "2023-03-01T21:26:35.1134406Z",
}

My object:

public class Time
{
     [JsonPropertyName(".issued")]
     [JsonConverter(typeof(DateTimeOffsetJsonConvertZulu))]
     public DateTimeOffset issued { get; set; }

     [JsonPropertyName(".expires")]
     [JsonConverter(typeof(DateTimeOffsetJsonConvertZulu))]
     public DateTimeOffset expires { get; set; }
}

The JSON Converter:


public class DateTimeOffsetJsonConvertZulu : JsonConverter<DateTimeOffset>
{
    public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert,
         JsonSerializerOptions options) =>
         DateTimeOffset.ParseExact(reader.GetString(), "yyyy-MM-ddThh:mm:ss.Z", CultureInfo.InvariantCulture);

   public override void Write(Utf8JsonWriter writer, DateTimeOffset value,
        JsonSerializerOptions options) =>
        writer.WriteStringValue(value.ToUniversalTime());
    }
}
Calling Code:

    
if (httpResponse.IsSuccessStatusCode && httpResponse.Content !=null)
{
   JsonSerializerOptions options= new JsonSerializerOptions() { WriteIndented = true };
                    options.Converters.Add(new DateTimeOffsetJsonConvertZulu());
                    serviceToken = JsonSerializer.Deserialize<CAPIServiceToken>(
                        await httpResponse.Content.ReadAsStringAsync())!;
}

The error: Exception when parsing date time string


I tried to change the format string but unclear how indicate the numbers after the "." and before the "Z".

I am assuming that they are the offset. In UTC I get a +- and the number of hours.
1

There are 1 answers

1
Ducky On

The completed Converter:

public class DateTimeOffsetJsonConvertZulu : JsonConverter<DateTimeOffset>
{
    public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert,
         JsonSerializerOptions options) =>
         DateTimeOffset.ParseExact(reader.GetString(), "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", CultureInfo.InvariantCulture);

   public override void Write(Utf8JsonWriter writer, DateTimeOffset value,
        JsonSerializerOptions options) =>
        writer.WriteStringValue(value.ToUniversalTime());
    }
}