我需要将类型为Dictionary的JSON字典反序列化为List(List),我正在使用JSON.Net来实现此目的。肯定它是一个令人惊叹的图书馆就是这样,我有点卡住了!
我正在订阅一些API,响应正如您所见:
"team_details": {
"0": {
"index": 1,
"team_id": "1..",
"team_name": "Research Team",
"team_url": "...",
"role": "Administrator"
},
"1": {
"index": 2,
"team_id": "2..",
"team_name": "WB Team",
"team_url": "...",
"role": "User"
}
}
我需要使用它将其转换为List<Team>
团队:
Class Teams{
public int Index{get;set;}
public String TeamName{get;set;}
...
}
答案 0 :(得分:2)
最简单的方法是反序列化为Dictionary<string, Team>
,然后在需要时使用dictionary.Values.ToList()
将值放入列表中。
但是,如果您真的希望在类定义中使用List<Team>
,则可以在反序列化期间使用自定义JsonConverter
进行转换。
public class TeamListConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<Team>));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
return token.Values().Select(v => v.ToObject<Team>()).ToList();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""team_details"": {
""0"": {
""index"": 1,
""team_id"": ""1.."",
""team_name"": ""Research Team"",
""team_url"": ""..."",
""role"": ""Administrator""
},
""1"": {
""index"": 2,
""team_id"": ""2.."",
""team_name"": ""WB Team"",
""team_url"": ""..."",
""role"": ""User""
}
}
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Team team in root.Teams)
{
Console.WriteLine(team.TeamName);
}
}
}
public class RootObject
{
[JsonProperty("team_details")]
[JsonConverter(typeof(TeamListConverter))]
public List<Team> Teams { get; set; }
}
public class Team
{
[JsonProperty("index")]
public int Index { get; set; }
[JsonProperty("team_id")]
public string TeamId { get; set; }
[JsonProperty("team_name")]
public string TeamName { get; set; }
[JsonProperty("team_url")]
public string TeamUrl { get; set; }
[JsonProperty("role")]
public string Role { get; set; }
}
输出:
Research Team
WB Team