【发布时间】:2021-08-06 13:31:45
【问题描述】:
我无意中在我的 ASP.NET Core 应用程序中切换到 System.Text.Json,从而在我的 API 中引入了一项重大更改。我有一个客户端正在发送 JSON 文档,并且使用数字 1 或 0 代替 true 或 false 来表示布尔字段:
// What they're sending.
{ "Active": 1 }
// What they should be sending.
{ "Active": true }
Newtonsoft.Json 库通过将数字转换为布尔值(0 = false,其他所有内容 = true)自动处理此问题,但 System.Text.Json 不这样做;它会引发异常。这意味着我的 API 端点突然停止为发送 1 和 0 的愚蠢客户端工作!
我似乎在迁移指南中找不到任何提及。我想将行为恢复到 Newtonsoft 处理它的方式,但我不确定是否有一个标志可以在我看不到的地方启用它,或者我是否必须编写一个自定义转换器。
有人可以帮我恢复像 Newtonsoft 的行为吗?
这里有一些代码来演示这个问题:
using System;
string data = "{ \"Active\": 1 }";
try
{
OutputState s1 = System.Text.Json.JsonSerializer.Deserialize<OutputState>(data);
Console.WriteLine($"OutputState 1: {s1.Active}");
}
catch (Exception ex)
{
Console.WriteLine($"System.Text.Json failed: {ex.Message}");
}
try
{
OutputState s2 = Newtonsoft.Json.JsonConvert.DeserializeObject<OutputState>(data);
Console.WriteLine($"OutputState 2: {s2.Active}");
}
catch (Exception ex)
{
Console.WriteLine($"Newtonsoft.Json failed: {ex.Message}");
}
public record OutputState(bool Active);
也是用于交互式游乐场的 .NET 小提琴:https://dotnetfiddle.net/xgm2u7
【问题讨论】:
-
在您的示例中,
System.Text.Json:System.Text.Json failed: Deserialization of reference types without parameterless constructor is not supported. Type 'OutputState'似乎不允许使用记录(尽管它适用于类)。 -
可以实现自定义转换器。你试过这种方法吗? docs.microsoft.com/en-us/dotnet/standard/serialization/…
-
@Métoule 这在 .NET 5 中是可能的。您可能使用的是 3.1 或更低版本:docs.microsoft.com/en-us/dotnet/standard/serialization/…
标签: c# json asp.net-core system.text.json