我希望你们能帮助我帮忙。我想拉出JSON文件中的每个ID但是我收到以下异常错误:
无法访问Newtonsoft.Json.Linq.JProperty上的子值。
private void button1_Click(object sender, EventArgs e)
{
string address = "https://api.mysportsfeeds.com/v1.1/pull/nba/2016-2017-regular/cumulative_player_stats.json?team=85";
var w = new WebClient();
w.UseDefaultCredentials = true;
w.Credentials = new NetworkCredential("****", "****");
var result = w.DownloadString(address);
var obj = JObject.Parse(result);
var play = "";
foreach (JProperty child in obj["cumulativeplayerstats"])
{
play = child["player"]["ID"].ToString();
string latlong = Convert.ToString(play);
Console.WriteLine("player=" + Convert.ToString(play));
Console.ReadKey();
}
}
以下是json的样子片段:
{
"cumulativeplayerstats": {
"lastUpdatedOn": "2017-09-11 4:45:30 PM",
"playerstatsentry": [
{
"player": {
"ID": "10138",
"LastName": "Abrines",
"FirstName": "Alex",
"JerseyNumber": "8",
"Position": "F"
},
"team": {
"ID": "96",
"City": "Oklahoma City",
"Name": "Thunder",
"Abbreviation": "OKL"
},
"stats": {
"GamesPlayed": {
"@abbreviation": "GP",
"#text": "68"
},
"Fg2PtAtt": {
"@category": "Field Goals",
"@abbreviation": "2PA",
"#text": "94"
},
"Fg2PtMade": {
"@category": "Field Goals",
"@abbreviation": "2PM",
"#text": "40"
},
"Fg3PtAtt": {
"@category": "Field Goals",
"@abbreviation": "3PA",
"#text": "247"
},
"Fg3PtMade": {
"@category": "Field Goals",
"@abbreviation": "3PM",
"#text": "94"
},
"FtAtt": {
"@category": "Free Throws",
"@abbreviation": "FTA",
"#text": "49"
},
"FtMade": {
"@category": "Free Throws",
"@abbreviation": "FTM",
"#text": "44"
}
}
},
我试着在这里挖掘,但我似乎无法找到一个有效的解决方案。如果你们能借出一些你们的智慧,我会非常感激!
谢谢民众!
答案 0 :(得分:3)
以JSON为例,如果您尝试查找名为“ID”的所有属性,只要它们位于层次结构的同一级别,您就可以使用“SelectTokens”方法路径和通配符,以达到您的财产级别。这可能会节省几行代码,是一种更好的定位方法。
.net这个解决方案的小提琴 - https://dotnetfiddle.net/fQ9xeH
foreach (var tokn in obj.SelectTokens("cumulativeplayerstats.playerstatsentry[*].*.ID"))
{
Console.WriteLine(tokn);
}
答案 1 :(得分:2)
您可以修改foreach
以遍历playerstatsentry
数组:
foreach (JObject child in obj["cumulativeplayerstats"]["playerstatsentry"].OfType<JObject>())
或没有OfType<T>
:
foreach (var child in obj["cumulativeplayerstats"]["playerstatsentry"])