Home > Mobile >  Deserialize json to bool from int
Deserialize json to bool from int

Time:07-09

Is there a way to configure deserialization so that when i try to deserialize json with value "1" to be parsed as bool value for an object.

Example class:

public class Values
{
    public bool BoolValue { get; set; }
}

and the json string:

var json = "{\"BoolValue\":1}";

When I try to do:

JsonSerializer.Deserialize<Values>(json);

logically it doesn't work because it expects to receive true or false but receive int value

Is there a way deserialize 1 and 0 to bool values???

CodePudding user response:

You can create a custom converter

public class BoolConverter : JsonConverter<bool>
{
    public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
    reader.TokenType switch
    {
        JsonTokenType.True => true,
        JsonTokenType.False => false,
        JsonTokenType.String => bool.TryParse(reader.GetString(), out var b) ? b : throw new JsonException(),
        JsonTokenType.Number => reader.TryGetInt64(out long l) ? Convert.ToBoolean(l) : reader.TryGetDouble(out double d) ? Convert.ToBoolean(d) : false,
        _ => throw new JsonException(),
    };

    public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
    {
        writer.WriteBooleanValue(value);
    }
}

And use it as an annotation:

[JsonConverter(typeof(BoolConverter))]
public bool Fav { get; set; }

Or as an configuration option:

var options = new JsonSerializerOptions
{
    Converters = { new BoolConverter() },
};
var values = JsonSerializer.Deserialize<Values>(json, options);

CodePudding user response:

Just set a condition, convert the string to int, dynamically set the bool variable by assigning a conditional statement that if the int is equal to 0 then yourBool = false, and if the integer = 1 then, yourBool = true. This will get the job done. If you're looking for a time complexity and more efficient way to do this I would recommend grabbing every instance and throwing it into a hashmap, and then from there converting each line in the array to split out the index of what bool you're looking for.

yourBool = false myInt = 0

Grab the parse of the this after you deserialize - convert to the property to an assigned equivalent from your very own bool "{"BoolValue":1}";

  • Related