我试图使用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);
如何访问反序列化的数据?
答案 0 :(得分:2)
首先,请注意此作品:但是,我不推荐它:
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对象({ {1}})):
{...}
您可以使用var summonerInfo = JsonConvert.DeserializeObject<List<WhateverThisIs>>(json);
foreach(var item in summonerInfo)
{
Console.WriteLine(item.LeagueName);
}
执行操作,但 工作比简单定义类型更多