0

在 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, 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<TClass, TDeclaredProperty, TRuntimeProperty, TConverter>.OnRead(ref ReadStack state, ref Utf8JsonReader reader) System.Text.Json。 JsonPropertyInfo.Read(JsonTokenType tokenType, ref ReadStack state, ref Utf8JsonReader reader) System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, ref Utf8JsonReader reader, ref ReadStack readStack) System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, ref Utf8JsonReader reader) System.Text.Json.JsonSerializer.Deserialize(string json, Type returnType,

这是它试图反序列化的数据片段。如果我从 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 core 3.1 mvc api 应用程序。

不知道为什么它不起作用。(也许,John Skeet 可以解释一下?)

4

1 回答 1

0

在做了一些研究并最终记住/意识到 JsonSerializerOptions 不能在当前版本的 System.Text.Json 中设置为全局之后,我终于能够通过在我需要的地方构建选项来使其按预期工作。这是代码片段,以防将来有人像我一样陷入困境。

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, 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; }
}
于 2020-10-15T20:30:35.307 回答