ASP.NET Core 3.1 Razor Page Web应用程序出现“ JsonException:JSON值无法转换为NodaTime.Instant”的NodaTime问题

问题描述

在ASP.NET Core 3.1 Razor Page纯前端Web应用程序中,我收到以下错误。

安装了以下软件包:

<PackageReference Include="System.Text.Json" Version="4.7.2" />
<PackageReference Include="EnumExtensions.System.Text.Json" Version="1.0.0" />
<PackageReference Include="NodaTime" Version="3.0.1" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.0.0" />

也可以在“启动”中进行设置:

services.AddRazorPages()
  .AddJsonOptions(options =>
  {
      // options.JsonSerializerOptions.PropertyNamingPolicy = null;
      // options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
      // options.JsonSerializerOptions.DictionaryKeyPolicy = null;

      options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null,true,true));
      //options.JsonSerializerOptions.IgnoreNullValues = true;
      options.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
      options.JsonSerializerOptions.Converters.Add(NodaConverters.IntervalConverter);
      options.JsonSerializerOptions.Converters.Add(NodaConverters.InstantConverter);
  })
  .AddRazorPagesOptions(options =>
  {
      options.Conventions.AddPageRoute("/Login","");
  });

JsonException:JSON值无法转换为NodaTime.Instant。路径:$。data [0] .created_at |行号:0 | BytePositionInLine:261。 System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) System.Text.Json.JsonPropertyInfoNotNullable .OnRead(ref ReadStack state,ref Utf8JsonReader reader) System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType,ref ReadStack状态,ref Utf8JsonReader阅读器) System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions选项,ref Utf8JsonReader阅读器,ref ReadStack readStack) System.Text.Json.JsonSerializer.ReadCore(Type returnType,JsonSerializerOptions options,ref Utf8JsonReader reader) System.Text.Json.JsonSerializer.Deserialize(字符串json,类型returnType,JsonSerializerOptions选项) System.Text.Json.JsonSerializer.Deserialize(字符串json,JsonSerializerOptions选项)

以下是要反序列化的数据片段。如果我从Instant切换到DateTimeOffset,它将“立即”运行(双关语:D)

{
    "data": [
        {
            "created_at": "2020-08-09T22:10:26.274672Z","updated_at": "2020-08-13T02:22:02.640871Z",}
    ],"page": 1,"size": 20,"count": 1,"total": 1,"success": true,"message": null
}

注意:此json数据是对对象进行序列化的结果,该对象确实包含类型(NodaTime)Instant的CreatedAt和UpdatedAt属性。我确认它可以与asp.net核心3.1 mvc api应用程序很好地工作。

不确定为什么它不起作用。 (也许,约翰·斯基特(John Skeet)可以阐明一些想法?)

解决方法

进行了一些研究并最终记住/意识到,无法在当前版本的System.Text.Json中将JsonSerializerOptions设置为全局设置,我终于可以通过在需要的地方构建选项来使其按预期工作。这是代码片段,以防将来有人像我一样被卡住。

var jsonString = "{\"data\":[{\"id\":\"f606942c-4740-46a7-be6f-66ceb38c530b\",\"created_at\":\"2020-08-09T22:10:26.274672Z\",\"updated_at\":\"2020-08-13T02:22:02.640871Z\"}],\"page\":1,\"size\":20,\"count\":1,\"total\":1,\"success\":true,\"message\":null }";
    
JsonSerializerOptions options = new JsonSerializerOptions();
options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null,true,true));

var response = JsonSerializer.Deserialize<Response>(jsonString,options);

    
public enum SampleType
{
    TYPE_0,TYPE_1
}

public class Sample
{
    [JsonProperty("id")]
    public string Id { get; set; } = System.Guid.NewGuid().ToString();
    [JsonProperty("created_at")]
    public Instant CreatedAt { get; set; }
    [JsonProperty("updated_at")]
    public Instant UpdateAt { get; set; }

    [JsonProperty("type")]
    public SampleType Type { get; set; }
}

public class Response
{
    [JsonProperty("data")]
    public IEnumerable<Sample> Data { get; set; }
    
    [JsonProperty("page")]
    public int Page { get; set; }
    
    [JsonProperty("size")]
    public int Size { get; set; }
    
    [JsonProperty("count")]
    public int Count { get; set; }
    
    [JsonProperty("total")]
    public int Total { get; set; }
    
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...