我想通过此JSON中的嵌套List
运行foreach循环。
我得到一些看起来像的JSON:
{
"name":"Placeholder",
"entries":
[
{
"playerId": "27271906",
"playerName": "Billy"
},
{
"playerId": "35568613",
"playerName": "Jeeves"
}
]
}
类:
public class IDs
{
public string playerId { get; set; }
}
public class Top
{
public List<IDs> entries { get; set; }
}
当我去运行该程序时,它似乎无法运行:
List<string> pros = new List<string>();
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var jss = new JavaScriptSerializer();
var ProsList = jss.Deserialize<List<IDs>>(jsonString);
int i = 1;
foreach (IDs x in ProsList)
{
pros.Add(x.playerId);
i++;
if (i == 3)
{
break;
}
}
}
当我按照这样设置它时,它会说我不能使用foreach
,因为没有枚举器。任何的想法?我是C#和这种语法的新手,所以有些人可能很容易看到它。谢谢!
我想补充说我正在使用Visual Studio 2013。
答案 0 :(得分:1)
您必须将json反序列化为Top
而不是List<IDs>
,并枚举result.entries
。将您的代码更改为
List<string> pros = new List<string>();
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var jss = new JavaScriptSerializer();
var result = jss.Deserialize<Top>(jsonString);
int i = 1;
foreach (IDs x in result.entries)
{
pros.Add(x.playerId);
i++;
if (i == 3)
{
break;
}
}
}
或者您也可以使用下面的JSON.NET
List<string> pros = new List<string>();
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var result = JsonConvert.DeserializeObject<Top>(jsonString);
int i = 1;
foreach (IDs x in result.entries)
{
pros.Add(x.playerId);
i++;
if (i == 3)
{
break;
}
}
}