JSonNet boolean serialization

Quick question:

In JSONNet - how do i get bool true/false to serialize as bool 1/0

I can see how we handle null values and all that just cant seem to find how to do this.

is this possible?


You can implement a custom converter like this:

[TestFixture]
public class CustomJsonSerialization
{
    [Test]
    public void Test()
    {
        string serializeObject = JsonConvert.SerializeObject(true, new BoolConverter());
        Assert.That(serializeObject, Is.EqualTo("1"));
        var deserializeObject = JsonConvert.DeserializeObject<bool>(serializeObject, new BoolConverter());
        Assert.That(deserializeObject, Is.True);
    }
}

public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((bool)value) ? 1 : 0);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value.ToString() == "1";
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }
}

Inspired by this response in similar question it can be solved like the following.

[JsonIgnore]
public bool SomeFlag { get; set; }

[JsonProperty(nameof(SomeFlag))]
public int SomeFlagAsInt
{
    get => SomeFlag ? 1 : 0;
    set => SomeFlag = value > 0;
}

@DavidPeden answer v2

Better string handling

/// <summary>
///  CUSTOM BOOLEAN -> 0 | 1 CONVERTER
/// </summary>
public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(bool.TryParse(value?.ToString(), out var parsed) ? (parsed ? 1 : 0) : 0);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return int.TryParse(reader.Value?.ToString(), out var parsed) && parsed == 1;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool) || objectType == typeof(bool?);
    }
}