json.net反序列化返回null

时间:2018-10-06 12:00:19

标签: c# json.net deserialization

我正在尝试将JSON字符串反序列化为C#对象。当我陷入调试器中时,JSON可视化程序似乎正在解析字符串。但是,当我通过以下代码推送字符串时,返回的对象的属性值为空值。

这是我的代码:

    public static Item GetPrices(string itemStr)
    {
        Item item = JsonConvert.DeserializeObject<Item>(itemStr);
        return item;
    }

    public class Item
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        [JsonProperty(PropertyName = "prices")]
        public Prices Prices { get; set; }
    }

    public class Prices
    {
        [JsonProperty(PropertyName = "priceUofM")]
        public PriceUofM[] PriceUofMs { get; set; }
    }

    public class PriceUofM
    {
        [JsonProperty(PropertyName = "uofm")]
        public string UofM { get; set; }

        [JsonProperty(PropertyName = "price")]
        public string Price { get; set; }
    }

这就是我要传递给它的内容:

{
    "item": {
        "id": "1A50CC070S",
        "prices": 
        [
            {
                "priceUofM": {
                    "uofm": "BOX",
                    "price": "$81.11"
                }
            },
            {
                "priceUofM": {
                    "uofm": "CASE",
                    "price": "$811.11"
                }
            }
        ]
    }
}

我已经通过多个在线解析器运行了它,所有这些解析器似乎都可以很好地解释JSON字符串。在格式化字符串导致JsonConvert.DeserializeObject失败时我做错了什么?

1 个答案:

答案 0 :(得分:0)

给出此json:

{
    "item": {
        "id": "1A50CC070S",
        "prices": 
        [
            {
                "priceUofM": {
                    "uofm": "BOX",
                    "price": "$81.11"
                }
            },
            {
                "priceUofM": {
                    "uofm": "CASE",
                    "price": "$811.11"
                }
            }
        ]
    }
}

C#模型为:

public class Model
{
    [JsonProperty("item")]
    public Item Item { get; set; }
}

public class Item
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("prices")]
    public List<Price> Prices { get; set; }
}

public class Price
{
    [JsonProperty("priceUofM")]
    public PriceUofM PriceUofM { get; set; }
}

public class PriceUofM
{
    [JsonProperty("uofm")]
    public string UofM { get; set; }

    [JsonProperty("price")]
    public string Price { get; set; }
}

为了将字符串反序列化为Item对象,JSON字符串类似于:

{
    "id": "1A50CC070S",
    "prices": 
    [
        {
            "priceUofM": {
                "uofm": "BOX",
                "price": "$81.11"
            }
        },
        {
            "priceUofM": {
                "uofm": "CASE",
                "price": "$811.11"
            }
        }
    ]
}