newtonsoft jsonconvert.deserializeObject将所有属性返回为null



我不知道这是怎么了:

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是包含两个产品的列表,但所有属性(codedescriptiontp)均为null。

为方便起见的格式JSON:

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

我已经看过类似的问题,但没有找到适用于这种情况的问题。如何解决?

谢谢。

您的JSON表示您需要围绕产品对象包装。例如:

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

使您 Return类看起来像这样:

public class Return
{
    [JsonProperty("products")]
    public List<ProductWrapper> Products { get; set; }
}

您可以使用@davidg提到的包装类以根据给定的JSON格式使其工作。但是,如果您不能更改班级,则必须将JSON调整为这种格式:

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

相关内容

  • 没有找到相关文章

最新更新