Joe*_*ght 4 .net c# jsonconvert system.text.json
如果我收到超出我控制范围的 JSON,它具有如下属性。
{"allow":"true"}
Run Code Online (Sandbox Code Playgroud)
我希望将其映射到boolC# 中的属性。
我发现我可以使用属性对数字做类似的事情
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
Run Code Online (Sandbox Code Playgroud)
但我怎样才能对布尔值做到这一点呢?
编辑:
我不确定为什么由于重复的问题而关闭此问题,因为另一个问题侧重于从整数转换为布尔值
好吧,看来这个功能不是内置的,但很容易实现。 https://github.com/dotnet/runtime/issues/43587#issuecomment-780031498
必须创建一个自定义转换器,如下所示(取自链接)。
public class BooleanConverter : JsonConverter<bool>
{
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.True:
return true;
case JsonTokenType.False:
return false;
case JsonTokenType.String:
return reader.GetString() switch
{
"true" => true,
"false" => false,
_ => throw new JsonException()
};
default:
throw new JsonException();
}
}
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
{
writer.WriteBooleanValue(value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3108 次 |
| 最近记录: |