嗨,我有一个用NewstonSoft JSON.NET反序列化为字符串var的JSON,它看起来像:
data = {"123456789": [{
"queue": "RANKED_SOLO_5x5",
"name": "Karthus's Captains",
"entries": [{
"leaguePoints": 37,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": true,
"losses": 124,
"playerOrTeamName": "Nickname",
"playerOrTeamId": "123456789",
"wins": 136
}],
"tier": "SILVER"
}]}
我想知道如何访问leaguePoints,例如,它位于"条目"中。提前感谢
如果您不想将JSON反序列化为具体的类(正如在这个非常类似的问题中所问的那样),您可以使用JSON.NET的JObject
-类,如下所示:
string jsonData = GetJsonStringFormSomewhere();
var jObject = (JObject)JsonConvert.DeserializeObject(jsonData);
var idOrWhatever = jObject["123456789"].First();
var firstEntry = idOrWhatever["entries"].First();
var leaguePoints = firstEntry["leaguePoints"].Value<int>();
Newtonsoft有不同的方法。一种不序列化到整个对象的方法可能是这样的;
JToken first = JObject.Parse(data);
JArray res = (JArray)first.SelectToken("123456789");
JToken entries = (JToken)JObject.Parse(res[0].ToString());
JArray result = JArray.Parse(entries.SelectToken("entries").ToString());
int leaguePoints = (int)result[0].SelectToken("leaguePoints");
我很快就完成了这项工作,并将其逐行拆分,这样你就可以看到每一步,但这意味着它不是很优雅,你当然可以将其连接起来,或者使用linq来获取数据。