JSonNet boolean serialization
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);
}
}
@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?);
}
}
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;
}