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; }
}
2
  • JSON.net allows you to do this, look at this question: stackoverflow.com/questions/1207731/… Commented Nov 28, 2012 at 13:05
  • Use JSON.NET. It is free and included by default in VS 2012. Commented Nov 28, 2012 at 13:06

2 Answers 2

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"]);
Sign up to request clarification or add additional context in comments.

2 Comments

You dont need to call it a var. You can see that it creates a dict.
ALso, i noticed, there may be issues when if there is a returned Array say: {prices:["a","b","c"]} dict["prices"];
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; }
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.