如果我收到超出我控制范围的 JSON,它具有如下属性。
{"allow":"true"}
Run Code Online (Sandbox Code Playgroud)
我希望将其映射到boolC# 中的属性。
我发现我可以使用属性对数字做类似的事情
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
Run Code Online (Sandbox Code Playgroud)
但我怎样才能对布尔值做到这一点呢?
编辑:
我不确定为什么由于重复的问题而关闭此问题,因为另一个问题侧重于从整数转换为布尔值
在 .Net Core 3.1 和使用System.Text.Json库中,我遇到了 Newtonsoft 库中没有出现的问题。
如果我在 JSON 中为某些类型(后端类型)DateTime?或 的属性发送一个空字符串int?,它会返回 400 状态代码,并带有一条错误消息,表示值无法反序列化。但是,对于 Newtonsoft,空字符串会自动解释为任何值的空值。Nullable<T>.
一个最小的例子是:
var json = "\"\"";
Assert.AreEqual(null, Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime?>(json)); // Passes
Assert.AreEqual(null, System.Text.Json.JsonSerializer.Deserialize<DateTime?>(json)); // Throws System.Text.Json.JsonException: The JSON value could not be converted to System.Nullable`1[System.DateTime].
Run Code Online (Sandbox Code Playgroud)
有没有办法让System.Text.Json行为以同样的方式?演示在这里。