gpt4 book ai didi

javascript - 使用带有嵌套 "list"的 .NET deserialize() 进行 JSON 解析

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:43 25 4
gpt4 key购买 nike

编辑:简化类

{
"name": "Final Five",
"bio": null,
"noPlayers": "0",
"roster": {
"players0": {
"playerId": "3516",
"name": "Gate",
"role": "Mid Lane",
"isStarter": 1
},
"players1": {
"playerId": "3826",
"name": "Veritas",
"role": "AD Carry",
"isStarter": 1
},
"players2": {
"playerId": "4054",
"name": "Novel",
"role": "Support",
"isStarter": 1
},
"players3": {
"playerId": "4142",
"name": "Wizardry",
"role": "Top Lane",
"isStarter": 0
},
"players4": {
"playerId": "4555",
"name": "Metroid",
"role": "Jungler",
"isStarter": 0
},
"players5": {
"playerId": "4554",
"name": "Chau",
"role": "Jungler",
"isStarter": 0
},
"players6": {
"playerId": "3847",
"name": "Biofrost",
"role": "Support",
"isStarter": 0
}
},
"logoUrl": "http://riot-web-cdn.s3-us-west-1.amazonaws.com/lolesports/s3fs-public/final-five-logo.png",
"profileUrl": "http://na.lolesports.com/node/3498",
"teamPhotoUrl": "http://na.lolesports.com/",
"acronym": "F5"
}

我收到了这个 json。我遇到的问题是试图将玩家解析为列表而不是单个元素,因为玩家的数量可能会有所不同。我试过使用数组和列表。这些是我设置的类

public class Player
{
public string playerId { get; set; }
public string name { get; set; }
public string role { get; set; }
public int isStarter { get; set; }
}

public class Roster
{
public Player players0 { get; set; }
public Player players1 { get; set; }
public Player players2 { get; set; }
public Player players3 { get; set; }
public Player players4 { get; set; }
public Player players5 { get; set; }
public Player players6 { get; set; }
}

public class Team
{
public string name { get; set; }
public object bio { get; set; }
public string noPlayers { get; set; }
public Roster roster { get; set; }
public string logoUrl { get; set; }
public string profileUrl { get; set; }
public string teamPhotoUrl { get; set; }
public string acronym { get; set; }
}

这是我的反序列化:

 Team team = new JavaScriptSerializer().Deserialize<Team>(responseText);

最佳答案

一种可能性是反序列化为动态对象,然后将其转换为强类型对象。像这样:

var dict = new JavaScriptSerializer().Deserialize<dynamic>(responseText);

生成的 dict 对象是一个字典,每个属性在字典中表示为一个名称-值对。嵌套对象,例如 roster 及其包含的 playersX 对象本身表示为字典。

因此,例如,您可以像这样获取 player1 对象的 name 属性:

Assert.AreEqual("Veritas", dict["roster"]["players1"]["name"]);

如果有帮助,您可以将 roster 属性设置为dynamic,如下所示:

public class Team
{
public string name { get; set; }
public object bio { get; set; }
public string noPlayers { get; set; }
public dynamic roster { get; set; }
public string logoUrl { get; set; }
public string profileUrl { get; set; }
public string teamPhotoUrl { get; set; }
public string acronym { get; set; }
}

然后只有该属性将被反序列化为字典的字典。

关于javascript - 使用带有嵌套 "list"的 .NET deserialize() 进行 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com