1

I have problems parsing some JSON data:

{
    "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"
}

I have tried a number of example but I cannot get any data from this example of product information. here is what I am trying to use:

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);

The text return right as above but the testJson is always null...

private class MyJsonClass
{   
    public IList<IDictionary<string, string>> data { get; set; }
}
live2
  • 3,771
  • 2
  • 37
  • 46
Aaron Gibson
  • 1,280
  • 1
  • 21
  • 36
  • JSON.net allows you to do this, look at this question: http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – mamoo Nov 28 '12 at 13:05
  • Use JSON.NET. It is free and included by default in VS 2012. – Levi Botelho Nov 28 '12 at 13:06

2 Answers2

4

This works with your 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"]);
L.B
  • 114,136
  • 19
  • 178
  • 224
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; }
    ...
}
Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56