在 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 可以解释一下?)