2015-04-20 25 views
2

我正在使用以下代碼從URL收集Json數據。在多個JObject級別循環並以字符串形式收集信息

  var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6"); 
      JObject jo = JObject.Parse(json); 
      JObject ja = (JObject)jo["rgDescriptions"]; 

      int cCount = 0; 
      int bCount = 0; 
      int eCount = 0; 

      foreach(var x in ja){ 

       // I'm stuck here. 
       string type = (Object)x["type"]; 

      } 

      CUAI.sendMessage("I found: " + ja.Count.ToString()); 

一切都運行良好,直到我到了foreach語句。
這是JSON數據的一部分。

{ 
    "success": true, 
    "rgInventory": { 
     "Blah other stuff" 
    }, 
    "rgDescriptions": { 
     "637390365_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "0RBITALIS Trading Card" 
     "175240190_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "Awesomenauts Trading Card" 
     }, 
     "195930139_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "CONSORTIUM Emoticon" 
     } 
    } 
} 

我通過rgDescriptions每個項目希望循環並獲得type數據作爲一個字符串,然後檢查它是否包含任何backgroundemoticontrading card
我知道我可以使用if(type.Contains("background"))來檢查項目類型是什麼,但是我在foreach循環中遇到了問題。

如果我使用foreach(JObject x in ja),我得到一個cannot convert type錯誤。
如果我使用foreach(Object x in ja)它提出了一個Cannot apply indexing of type object
當我使用foreach(var x in ja)string type = (JObject)x["type"];

這個錯誤也會發生嗎?有誰能告訴我我做錯了嗎?

回答

3

你在你的JSON中有一些錯誤。用jsonlint.com檢查它。我認爲應該是這個樣子:

{ 
    "success": true, 
    "rgInventory": { 
     "Blah other stuff": "" 
    }, 
    "rgDescriptions": { 
     "637390365_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "0RBITALIS Trading Card" 
     }, 
     "175240190_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "Awesomenauts Trading Card" 
     }, 
     "195930139_0": { 
      "appid": "753", 
      "background_color": "", 
      "type": "CONSORTIUM Emoticon" 
     } 
    } 
} 

可以使用JProperty,JToken和SelectToken方法來獲取類型:

var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6"); 
JObject jo = JObject.Parse(json); 

foreach (JProperty x in jo.SelectToken("rgDescriptions")) 
{ 
    JToken type = x.Value.SelectToken("type"); 
    string typeStr = type.ToString().ToLower(); 

    if (typeStr.Contains("background")) 
    { 
     Console.WriteLine("Contains 'background'"); 
    } 
    if (typeStr.Contains("emoticon")) 
    { 
     Console.WriteLine("Contains 'emoticon'"); 
    } 
    if (typeStr.Contains("trading card")) 
    { 
     Console.WriteLine("Contains 'trading card'"); 
    } 
} 
+1

謝謝你把我介紹給'SelectToken'!我必須閱讀更多關於使用這個。另外,非常感謝您的幫助。代碼工作完美。 :) – Kain