我需要使用 .NET 的
System.Text.Json
反序列化一个包含 UTC 日期时间的 JSON 字符串,但我无法使用 NodaTime 转换器来表示 Instant
,因为该字符串缺少最后的 Z
(即使它是 UTC) ).
我正在使用以下代码:
public record Item(Instant date);
var options = new JsonSerializerOptions()
.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var item = JsonSerializer.Deserialize<Item>(options);
我收到以下错误:
---> System.Text.Json.JsonException: Cannot convert value to NodaTime.Instant
---> NodaTime.Text.UnparsableValueException: The value string does not match a quoted string in the pattern. Value being parsed: '2023-10-20T10:10:22^'. (^ indicates error position.)
解决方案是手动构建所需格式的转换器:
var options = new JsonSerializerOptions
{
Converters =
{
new NodaPatternConverter<Instant>(InstantPattern.CreateWithInvariantCulture("uuuu-MM-ddTHH:mm:ss"))
}
};
如果您想使用其他类型执行此操作,例如使用
LocalDateTime
和默认转换器不支持的格式,则类似的事情:
var options = new JsonSerializerOptions
{
Converters =
{
new NodaPatternConverter<LocalDateTime>(LocalDateTimePattern.CreateWithInvariantCulture("uuuu-MM-dd HH:mm:ss"))
}
};