System.Text.Json: How to convert from "true" to boolean
Asked Answered
O

2

6

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

Overstate answered 11/1, 2023 at 22:18 Comment(2)
This was closed as duplicate cause it covers strings also - check out the answer.Conference
#68682950Conference
O
18

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);
    }
}
Overstate answered 11/1, 2023 at 22:24 Comment(1)
Very helpful answer... I've streamlined the code, added a helpful exception message, made it case-insensitive and shared it out in my Gist here: gist.github.com/cajuncoding/00896396fdeddabdd661aca8524165d1Semiotics
S
-3

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}
Sontag answered 12/1, 2023 at 1:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.