52

I am calling a webservice and the returned data for a bool field is either 0 or 1 however with my model I am using a System.Bool

With Json.Net is it possible to cast the 0/1 into a bool for my model?

Currently I am getting an error

Newtonsoft.Json.JsonSerializationException: Error converting value "0" to type 'System.Boolean'

Any help would be awesome!!

Diver Dan
  • 9,953
  • 22
  • 95
  • 166

1 Answers1

118

Ended up creating a converter:

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

Then within my model:

 [JsonConverter(typeof(BoolConverter))]
    public bool active { get; set; }
starball
  • 20,030
  • 7
  • 43
  • 238
Diver Dan
  • 9,953
  • 22
  • 95
  • 166
  • 4
    Depending on the situation, you may also need `bool?` in `CanConvert` – Jorge Yanes Diez Jul 06 '16 at 10:41
  • 5
    And is there possibly a way to apply this custom converter to all bool properties throughout all objects without adding JsonConverter attributes? – Grengas Jun 07 '17 at 08:55
  • Changing the `ReadJson` to `return reader.Value != null && reader.Value.ToString() == "1";` will account for null values – Alex Feb 28 '23 at 13:20