使用 System.Text.Json 反序列化带有 UTC/Zulu 时间字符串的 JSON

问题描述 投票:0回答:1

我在反序列化具有祖鲁格式时间字符串的 JSON 时遇到一些问题。我继续收到一个异常,指出该字符串不是数据和时间。

我从 REST 服务返回以下字符串。

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

我的对象:

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

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

JSON 转换器:


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

错误:


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.
c# json system.text.json jsonserializer jsonconverter
1个回答
0
投票

完成的转换器:

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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.