我使用以下代码从URL收集Json数据。
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
数据作为字符串获取,然后检查它是否包含background
,emoticon
或{{1 }}。
我知道我可以使用trading card
来检查项目类型是什么,但我遇到了foreach循环问题。
如果我使用if(type.Contains("background"))
,我会收到foreach(JObject x in ja)
错误
如果我使用cannot convert type
它会出现foreach(Object x in ja)
使用Cannot apply indexing of type object
和foreach(var x in ja)
有谁能告诉我我做错了什么,拜托?
答案 0 :(得分: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'");
}
}