代码之家  ›  专栏  ›  技术社区  ›  Marc.2377

newtonSoft jsonConvert.DeserializeObject将所有属性返回为空

  •  2
  • Marc.2377  · 技术社区  · 6 年前

    我不知道这是怎么回事:

    public class Product
    {
        public string code { get; set; }
        public string description { get; set; }
        public string tp { get; set; }
    }
    
    public class Return
    {
        [JsonProperty("products")]
        public List<Product> Products { get; set; }
    }
    
    public class BlingJson
    {
        [JsonProperty("return")]
        public Return Return { get; set; }
    }
    
    public static void Run()
    {
        string str = "{ \"return\": { \"products\": [ { \"product\": { \"code\": \"8147-048PA\", \"description\": \"LEGEND 220v - HAIR CUTTER\", \"tp\": \"P\" } }, { \"product\": { \"code\": \"08164-148PA\", \"description\": \"FINALE - HAIR CUTTER\", \"tp\": \"P\" } } ] } }";
    
        BlingJson json = JsonConvert.DeserializeObject<BlingJson>(str);
    }
    

    反序列化后, json.Return.Products 是包含两个产品的列表,但所有属性( code , description tp )为空。

    为方便起见,格式化JSON:

    {
        "return": {
            "products": [
                {
                    "product": {
                        "code": "8147-048PA",
                        "description": "LEGEND 220v - HAIR CUTTER",
                        "tp": "P"
                    }
                },
                {
                    "product": {
                        "code": "08164-148PA",
                        "description": "FINALE - HAIR CUTTER",
                        "tp": "P"
                    }
                }
            ]
        }
    }
    

    我看到过类似的问题,但没有找到适用于这个案例的问题。 如何解决?

    谢谢。

    2 回复  |  直到 6 年前
        1
  •  3
  •   DavidG    6 年前

    JSON意味着您需要在产品对象周围使用包装器。例如:

    public class ProductWrapper
    {
        public Product Product { get; set; }
    }
    

    这使你 Return 类如下:

    public class Return
    {
        [JsonProperty("products")]
        public List<ProductWrapper> Products { get; set; }
    }
    
        2
  •  0
  •   kowsikbabu    6 年前

    您可以使用@davidg提到的包装类,使其按照给定的JSON格式工作。但是,如果无法更改类,则必须将JSON调到以下格式:

    {"return":
        {"products":
            [
                {"code":"A","description":"B","tp":"C"},
                {"code":"D","description":"E","tp":"F"}
            ]
        }
    }