[英]How do I access this deserialized data?
我正在嘗試使用Newtonsoft json.NET解析一些json數據。
我可以反序列化數據,但是當我嘗試使用反序列化的數據時,出現錯誤“'Newtonsoft.Json.Linq.JArray'不包含'leagueName'的定義”。
這是我要使用的Json數據。
[
{
"queueType": "RANKED_SOLO_5x5",
"hotStreak": false,
"wins": 6,
"veteran": false,
"losses": 10,
"playerOrTeamId": "39257940",
"tier": "SILVER",
"playerOrTeamName": "Kristmas Tree",
"inactive": false,
"rank": "V",
"freshBlood": false,
"leagueName": "Fizz's Gladiators",
"leaguePoints": 47
},
{
"queueType": "RANKED_FLEX_SR",
"hotStreak": true,
"wins": 100,
"veteran": true,
"losses": 99,
"playerOrTeamId": "39257940",
"tier": "SILVER",
"playerOrTeamName": "Kristmas Tree",
"inactive": false,
"rank": "I",
"freshBlood": false,
"leagueName": "Xin Zhao's Heralds",
"leaguePoints": 57
}
]
這是我嘗試打印“ hotStreak”的嘗試
var json = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/39257940?api_key=xxxx-xxxx-xxxx-xxxxxxxx");
MessageBox.Show(json); // gives me the desired data
var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
var leagueName = summonerInfo.leagueName;
MessageBox.Show(leagueName);
如何訪問反序列化的數據?
首先,請注意, 這是可行的 :但是,我不建議這樣做:
var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
foreach(var item in summonerInfo)
{
Console.WriteLine(item.leagueName);
}
相反,我建議的是:
首先,定義與JSON匹配的類型:
class WhateverThisIs // rename me!
{
public string QueueType { get; set; }
public bool HotStreak { get; set; }
public int Wins { get; set; }
// ...
public string LeagueName { get; set; }
public int LeagueWins { get; set; }
}
現在, 以該類型反序列化-在您的情況下,進入列表或數組(JSON中的根對象是JSON數組( [...]
),而不是JSON對象( {...}
)):
var summonerInfo = JsonConvert.DeserializeObject<List<WhateverThisIs>>(json);
foreach(var item in summonerInfo)
{
Console.WriteLine(item.LeagueName);
}
您可以使用dynamic
來做事情,但是它比簡單地定義類型要多得多 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.