System.Text.Json
时,不小心引入了一个破坏性变化。我有一个客户端正在发送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失败:不支持没有无参构造函数的引用类型的反序列化。类型“OutputState”
(但它可以使用类)。 - Métoule