Search code examples
asp.net-core.net-corejsonconvert

Setting a boolean property from a 3rd party endpoint that returns a string


I am attempting to deserialize a json object using JsonConvert - the data is coming from a 3rd party API

return JsonConvert.DeserializeObject<UserRegistration>(content,
                    JsonSnakeCaseNameStrategySettings.Settings());

The UserRegistration class:

public class UserRegistration
    {
        public UserRegistrationData UserRegistration { get; set; }
    }

    public class UserRegistrationData
    {
        public int UserId { get; set; }

        public string Email { get; set; }

        public UserRegistrationCustomFields CustomFields { get; set; }
    }

    public class UserRegistrationCustomFields
    {
        private bool emailDelivery;
        public string DeliveryTime { get; set; }

        public bool EmailDelivery {
            get
            {
                return emailDelivery;
            }
            set
            {
                emailDelivery = value.ToString() == "1";
            }
        }

        public bool SmsDelivery { get; set; }

        public string PhoneNumber { get; set; }
    }

I've tried several ways, this is my current iteration. The goal is to have "EmailDelivery" be a boolean, the value from the API will always be "1" or "0". This throws a JsonReaderException: Could not convert string to boolean: 0. Path 'user_registration.custom_fields.email_delivery', line 1, position 208.


Solution

  • You need custom JsonConverter to modify the deserialize principle.

    Change your model like below:

    public class UserRegistrationCustomFields
    {
        public string DeliveryTime { get; set; }
    
        public bool EmailDelivery{get;set;}
    
        public bool SmsDelivery { get; set; }
    
        public string PhoneNumber { get; set; }
    }
    

    Custom a JsonConverter:

    public class JsonBooleanConverter : JsonConverter
    {
        public override bool CanWrite { get { return false; } }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = reader.Value.ToString().ToLower().Trim();
            switch (value)
            {
    
                case "1": return true;
            }
            return false;
        }
    
        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(Boolean))
            {
                return true;
            }
            return false;
        }
    }
    

    How to use:

    JsonConvert.DeserializeObject<UserRegistration>(json, new JsonBooleanConverter());