2012-11-28 179 views
1

我有麻煩牧師一些JSON數據:C#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; } 
    } 
+0

JSON.net可以讓你做到這一點,看一下這個問題: http://stackoverflow.com/questions/1207731/how-can-i -deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – mamoo

+0

使用JSON.NET。它是免費的,默認包含在VS 2012中。 –

回答

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"]); 
+1

你不需要稱它爲var。你可以看到它創建了一個字典。 – Fallenreaper

+0

此外,我注意到,如果有返回的數組可能會出現問題: {prices:[「a」,「b」,「c」]} dict [「prices」]; – Fallenreaper

1

如果json對象的字段總是相同的,那麼你可以使用強類型類而不是字典。該JSON序列將正確序列如下類別:

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; } 
    ... 
}