-3

Is there any built in settings in json.net to disable the conversion of numbers to booleans. I would prefer it to return an error instead : (without writing a Custom Converter for each class that has a bool property )


    public class MyClass
    {
        public bool flag { get; set; }
    }

    var str = @"{"flag":123}";
    MyClass result = JsonConvert.DeserializeObject<MyClass>(str) ; // flag is true !




mLar
  • 2,967
  • 2
  • 22
  • 23

2 Answers2

1

You shouldn't use different types in one property to get one bool result. But if you wish not to declare one custom JsonConvert for every property in the class, you can always create DefaultSettings in your code.

void Initialize()
{
    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
        Converters = new List<JsonConverter>
        {
            new BoolJsonConverter()
        }
    };
}

// Create JsonConvert you want to add to DefaultSettings
public class BoolJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

    }
}

var json = @"{""flag"":123}"
var myClass = JsonConvert.DeserializeObject<MyClass>(json);
Miro J.
  • 4,270
  • 4
  • 28
  • 49
0

I'm assuming this is a Deserialize only situation. If that is the case, you could have your int value go into an int and use another var to hold the bool. Something like -

public class MyClass
{
    public int flagInt { get; set; }

    [JsonIgnore]
    public bool flag
    {
        get
        {
            switch (flagInt)
            {
                case 0: return false;
                case 1: return true;
                default: throw new Exception("Cannot convert flag to bool");
            }
        }
    }
}

Note that I don't have a setter on flag so doing something like flag = false will not have expected results and will not serialize correctly either.

OliveJuice
  • 368
  • 1
  • 7
  • 1
    good trick, but it needs to be implemented on every boolean property of every class of the application – mLar Feb 04 '20 at 22:54