If I receive JSON which is beyond my control, which has a property as follows.
{"allow":"true"}
and I want that to map to a bool
property in C#.
I saw that I can do similar for numbers using the attribute
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
but how can I do that for booleans?
Edit:
I am not sure why this is closed because of a duplicate question, since the other question focuses on converting from ints to bools
CodePudding user response:
Ok, it seems like this functionality is not built in but is easy to implement. https://github.com/dotnet/runtime/issues/43587#issuecomment-780031498
Would have to create a custom converter as follows (taken from the link).
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);
}
}
CodePudding user response:
Just for a record, any converters take a time and memory. So if you have not very many string bool properies in your json string, the easiest and the most sufficient way would be to fix the json string
var json="{\"allow\":\"true\"}";
json=json.Replace("\"true\"","true").Replace("\"false\"","false");
output
{"allow":true}