代码之家  ›  专栏  ›  技术社区  ›  Oleg Sh

newtonsoft-反序列化为条件bool属性[重复]

  •  0
  • Oleg Sh  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有以下JSON对象:

      {
        "entity": "Customer",
        "id": "XXX",
        "isActive": "1",
        "createdTime": "2018-01-30T18:56:51+02:00",
        "updatedTime": "2019-01-05T02:15:17+02:00",
    

    以及以下DTO类:

    public class Customer
    {
        public string Id { get; set; }
        public bool IsActive { get; set; }
        public DateTime CreatedTime { get; set; }
        public DateTime UpdatedTime { get; set; }
    }
    

    反序列化代码:

            var jsonResponse = JObject.Parse(customerString);
            JToken array = jsonResponse["response_data"];
            List<Customer> result = (List<Customer>)array.ToObject(typeof(List<Customer>));
    

    但是我有个问题 IsActive 属性,因为JSON对象有1或0个值,但我希望有布尔值。如何编写JSonserializer来完成它?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Manoj Choudhari    6 年前

    皮特的密码很好 how to get newtonsoft to deserialize yes and no to boolean

    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 "true":
            case "yes":
            case "y":
            case "1":
                return true;
        }
        return false;
    }
    
    public override bool CanConvert(Type objectType)
    {
        if (objectType == typeof(Boolean))
        {
            return true;
        }
        return false;
    }
    

    }

    用途:

    var myObj = JsonConvert.DeserializeObject<T>(json, new JsonBooleanConverter())