1

我在解析一些 JSON 数据时遇到问题:

{
    "title": "LED SIDE DIRECTION INDICATOR 9-33V CATEGORY 6, 19cm CABLE CHROME BASE  LED AUTO LAMPS",
    "user_price": {
        "inc_tax_value": 34.067,
        "ex_tax_value": 30.97,
        "base_inc_tax": 34.067,
        "base_ex_tax": 30.97,
        "currency_code": "",
        "price_rule": "35"
    },
    "local_quantity": 0,
    "global_quantity": 0,
    "url": "http://ishop2.cooldrive.com.au/products/3102CM",
    "all_warehouse_quantity": 0,
    "description1": "LED SIDE DIRECTION INDICATOR",
    "description2": "9-33V CATEGORY 6, 19cm CABLE",
    "description3": "CHROME BASE  LED AUTO LAMPS",
    "price_per": 1,
    "default_pack_quantity": 1,
    "code": "3102CM"
}

我尝试了许多示例,但无法从此产品信息示例中获取任何数据。这是我想要使用的:

string testJson = new HttpHelper().POST("http://ishop2.cooldrive.com.au/api/product", "code=3102CM");
        System.Windows.Forms.Clipboard.SetText(testJson);
        MyJsonClass tester = new System.Web.Script.Serialization.JavaScriptSerializer()
            .Deserialize<MyJsonClass>(@testJson);

文本如上返回,但 testJson 始终为空......

private class MyJsonClass
{   
    public IList<IDictionary<string, string>> data { get; set; }
}
4

2 回答 2

4

这适用于您的 json

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(testJson);

Console.WriteLine(dict["url"]);

var price = (Dictionary<string, object>)dict["user_price"];
Console.WriteLine(price["inc_tax_value"]);
于 2012-11-28T13:08:44.197 回答
1

If the fields of the json object are always the same, then you could use strong typed classes instead of dictionaries. The json serializer will serialize correctly to the following classes:

private class MyJsonClass
{
    public string title { get; set; }
    public UserPrice user_price { get; set; }
    public int local_quantity { get; set; }
    ...
}

private class UserPrice
{
    public decimal inc_tax_value { get; set; }
    public decimal ex_tax_value { get; set; }
    ...
}
于 2012-11-28T13:17:25.137 回答