C# 无法访问 Newtonsoft.Json.Linq.JProperty 上的子值
Posted
技术标签:
【中文标题】C# 无法访问 Newtonsoft.Json.Linq.JProperty 上的子值【英文标题】:C# Cannot access child value on Newtonsoft.Json.Linq.JProperty 【发布时间】:2018-03-10 19:47:00 【问题描述】:我希望你们能帮助我。我想提取 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 的外观的 sn-p:
"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"
,
我尝试在这里挖掘,但似乎找不到有效的解决方案。诸位若能出点圣人之智,不胜感激!
谢谢大家!
【问题讨论】:
这里只是一个猜测,但是当查看cumulativeplayerstats
的第一个孩子时,它会不会呕吐,即"lastUpdatedOn": "2017-09-11 4:45:30 PM",
,该节点下没有player
节点...跨度>
@TylerLee 我也是这么想的,但是当我更新 play = child["lastUpdatedOn"].ToString();我仍然收到同样的错误。
【参考方案1】:
您可以修改您的 foreach
以遍历 playerstatsentry
数组:
foreach (JObject child in obj["cumulativeplayerstats"]["playerstatsentry"].OfType<JObject>())
或者没有OfType<T>
:
foreach (var child in obj["cumulativeplayerstats"]["playerstatsentry"])
【讨论】:
【参考方案2】:以您的 JSON 为例,如果您尝试定位所有名为“ID”的属性,只要它们位于层次结构的同一级别,您可以使用 "SelectTokens" 方法使用路径和通配符以达到您的属性级别。这可能会节省几行代码,是一种更好的定位方式。
.net Fiddle 这个解决方案 - https://dotnetfiddle.net/fQ9xeH
foreach (var tokn in obj.SelectTokens("cumulativeplayerstats.playerstatsentry[*].*.ID"))
Console.WriteLine(tokn);
【讨论】:
如果它对你有用,请接受这个答案。以上是关于C# 无法访问 Newtonsoft.Json.Linq.JProperty 上的子值的主要内容,如果未能解决你的问题,请参考以下文章