Convert an int to bool with Json.Net

C# 4.0json.netDeserialization

C# 4.0 Problem Overview


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!!

C# 4.0 Solutions


Solution 1 - C# 4.0

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

hope this helps someone else

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiver DanView Question on Stackoverflow
Solution 1 - C# 4.0Diver DanView Answer on Stackoverflow