Rick Rick - 11 days ago 6
C# Question

How to Serialise/Deserialise when web service sends a bool but receives an int

Currently working with the most annoying web service! I'm using Newtonsoft Json.Net.

When I request data, a bool property

EndOfDay
is sent as
true
or
false
- deserialize works fine BUT annoyingly, when I send data to the web service, for this same field I have to send either a 0 or 1 - don't ask why as I couldn't give you a good answer - All I know is I can't change it.

Is there a way of serializing bools to 0 or 1 even though when I deserialize the strings will be true/false or should I admit defeat and have separate objects which are almost identical except for this one property - one object has a bool and the other an int?

Evk Evk
Answer

One way to do it is to use custom conveter:

class Test {
    [JsonConverter(typeof(StrangeBoolConverter))]
    public bool EndOfDay { get; set; }

    private class StrangeBoolConverter : JsonConverter {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
            // write it as 1 or 0
            writer.WriteValue((bool) value ? 1 : 0);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
            // but when reading - expect "true" or "false"
            return Convert.ToBoolean(reader.Value);
        }

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

Test

var test = JsonConvert.DeserializeObject<Test>("{\"EndOfDay\":\"true\"}");
var back = JsonConvert.SerializeObject(test); // {"EndOfDay": "1"}
Comments