我打电话给Riot Games API https://developer.riotgames.com/ 它在JSON中返回this huge output(链接到pastebin)。
JSON包含6"参与者"我想从输出中创建6个参与者对象。我的问题是还有其他部分而不是"参与者"例如" gameid"," gamestarttime"因此,我不知道如何只读出"参与者下面的JSON文本:"部分。
简而言之,我如何才能单独输出"参与者"或者我如何只创建"参与者"输出部分?
如果除了参与者之外没有任何其他内容,这是我的代码:
// Create a string containing the output from the API call
var jsonString = GetResponse("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/79200188?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxx");
// Create a list of Participants containing the data from the JSON
var participantsList = JsonConvert.DeserializeObject<List<Participant>>(jsonString);
// Show the names of the participants
foreach (var item in participantsList)
{
MessageBox.Show(item.summonerName);
}
这是我的Participant类,我想从中创建JSON中的对象。
class Participant
{
public int profileIconId { get; set; }
public int championId { get; set; }
public string summonerName { get; set; }
public bool bot { get; set; }
public int spell2Id { get; set; }
public int teamId { get; set; }
public int spell1Id { get; set; }
public int summonerId { get; set; }
}
答案 0 :(得分:1)
根据我的评论,json.net只反序列化它可以在模型中找到的字段。因此,只需在模型中放置要从json中获取的字段。
POCO示例:
public class GameData {
public string gameId {get; set;}
public int mapId {get; set;} //just demonstrating that it only fills in the fields you put in the model
public List<Participant> participants = new List<Participant>();
}
...
public class Participant
{
public int profileIconId { get; set; }
public int championId { get; set; }
public string summonerName { get; set; }
public bool bot { get; set; }
public int spell2Id { get; set; }
public int teamId { get; set; }
public int spell1Id { get; set; }
public int summonerId { get; set; }
}
反序列化如下:
var gameInfo = JsonConvert.DeserializeObject<GameData>(jsonString);
var participantsList = gameInfo.participants;
答案 1 :(得分:0)
如果您在创建另一个模型时没有问题,那么创建一个基本模型
public class GameData
{
public string gameId {get; set;}
public int mapId {get; set;}
public List<Participant> participants
}
并使用
var gameData =JsonConvert.DeserializeObject<GameData>(jsonString);
如果您不想再创建一个模型,可以将jsonString转换为Jobject,然后提取出唱歌值或从该值反序列化 例如,
var jsonString = GetResponse("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/79200188?api_key=RGAPI-dc7c328a-dd2b-40ca-8ccd-71d05d530a4e");
JObject json = JObject.Parse(jsonString);
var gameId = json .GetValue("filetype").ToString();
您也可以这样做以提取其他值