Search code examples
c#.netsystem.text.jsonjsonconvert

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


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


Solution

  • 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);
        }
    }