从 returns 字符串的第 3 方端点设置布尔值 属性

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

我正在尝试使用 JsonConvert 反序列化 json 对象 - 数据来自第三方 API

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

用户注册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; }
    }

我尝试了几种方法,这是我目前的迭代。目标是让“EmailDelivery”成为布尔值,API 中的值将始终为“1”或“0”。这会引发 JsonReaderException:Could not convert string to boolean: 0. Path 'user_registration.custom_fields.email_delivery', line 1, position 208.

需要自定义JsonConverter修改反序列化原理

像下面这样更改您的模型:

public class UserRegistrationCustomFields
{
    public string DeliveryTime { get; set; }

    public bool EmailDelivery{get;set;}

    public bool SmsDelivery { get; set; }

    public string PhoneNumber { get; set; }
}

自定义一个 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;
    }
}

使用方法:

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