gpt4 book ai didi

c# - System.FormatException : The JSON value is not in a supported DateTimeOffset format

转载 作者:行者123 更新时间:2023-12-04 07:33:23 28 4
gpt4 key购买 nike

我正在阅读这篇关于日期时间相关格式支持的 MSDocs 文章
https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support#support-for-the-iso-8601-12019-format
我只是想弄清楚默认配置没有按预期工作,或者我一定遗漏了一些东西。
我的意思是:

DateTimeOffset.Parse("2021-03-17T12:03:14+0000");
工作得很好。

JsonSerializer.Deserialize<TestType>(@"{ ""CreationDate"": ""2021-03-17T12:03:14+0000"" }");
没有。
例子:
using System;
using System.Text.Json;
using System.Threading.Tasks;


namespace CSharpPlayground
{
public record TestType(DateTimeOffset CreationDate);

public static class Program
{
public static void Main()
{
var dto = DateTimeOffset.Parse("2021-03-17T12:03:14+0000");
Console.WriteLine(dto);

var testType = JsonSerializer.Deserialize<TestType>(@"{ ""CreationDate"": ""2021-03-17T12:03:14+0000"" }");
Console.WriteLine(testType.CreationDate);
}
}
}
抛出以下异常:
System.Text.Json.JsonException: The JSON value could not be converted to CSharpPlayground.TestType. Path: $.CreationDate | LineNumber: 0 | BytePositionInLine: 44.
---> System.FormatException: The JSON value is not in a supported DateTimeOffset format.

最佳答案

使用 System.Text.Json 实现自定义 JSON 行为通常使用自定义转换器完成。不幸的是,对于不同的日期格式并没有提供很多开箱即用的工具,因此如果您需要反序列化默认设置中没有的内容 ISO 8601-1:2019格式你需要自己滚动。
幸运的是,这不是很困难:

   using System.Text.Json;
using System.Text.Json.Serialization;

public class DateTimeOffsetConverterUsingDateTimeParse : JsonConverter<DateTimeOffset >
{
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Debug.Assert(typeToConvert == typeof(DateTimeOffset));
return DateTimeOffset .Parse(reader.GetString());
}

public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}


通过这种方式,您将获得与使用 DateTimeOffset.Parse() 时相同的行为。 .
你可以像这样使用它
    public record TestType(DateTimeOffset CreationDate);
public class Program
{
public static void Main(string[] args)
{
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeOffsetConverterUsingDateTimeParse());

var testType = JsonSerializer.Deserialize<TestType>(@"{ ""CreationDate"": ""2021-03-17T12:03:14+0000"" }",options);
Console.WriteLine(testType.CreationDate);
}
}


关于c# - System.FormatException : The JSON value is not in a supported DateTimeOffset format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67857022/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com