c# - json.net 将元素映射到集合

标签 c# json.net

我得到一个如下所示的 json 对象。

{
    "result": {
        "status": 1,
        "teams": [
            {
                "team_id": 1838315,
                "name": "Team Secret",
                "tag": "Secret",
                "time_created": 1408993713,
                "rating": "inactive",
                "logo": 543025270456493060,
                "logo_sponsor": 540768028333677400,
                "country_code": "",
                "url": "http://www.teamsecret.gg/",
                "games_played_with_current_roster": 0,
                "player_0_account_id": 41231571,
                "player_1_account_id": 73562326,
                "player_2_account_id": 82262664,
                "player_3_account_id": 86745912,
                "player_4_account_id": 87278757,
                "admin_account_id": 5390881,
                "league_id_0": 1803,
                "league_id_1": 1886,
                "league_id_2": 1936,
                "league_id_3": 1942,
                "league_id_4": 2129,
                "league_id_5": 2140,
                "league_id_6": 2158,
                "league_id_7": 2339,
                "league_id_8": 2418,
                "league_id_9": 2661,
                "league_id_10": 2877
            }
        ]
    }
}

我想使用Newtonsoft json.net libaray来反序列化对象。 大部分都很简单,但我不太确定如何处理player_X_account_id和 league_id_X。

两者都或多或少具有无限数量的元素。 但由于它们不是映射为列表而是单个元素,我不太确定如何将它们映射到我的 .Net 对象中。

我可以创建一百个每种类型的成员,但这并不是特别好。 我最好将它们映射到某种集合,但我不知道如何完成或者是否可能。

知道如何做到这一点吗?

编辑:我无法控制我得到的 json 对象,它是对 SteamWebAPI 的调用

最佳答案

您可以使用extension data feature of JSON.NET :

public class Team
{
    public int Team_Id { get; set; }
    public string Name { get; set; }
    public string Tag { get; set; }
    public string Url { get; set; }
    //other properties

    [JsonExtensionData]
    public IDictionary<string, JToken> AdditionalData { get; set; }
}

然后您可以通过枚举AdditionalData属性来检查联盟和玩家ID的属性。

关于c# - json.net 将元素映射到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30256250/

相关文章:

c# - 混淆后的 .Net C# 应用程序可以被反编译吗?

c# - 基于参数抛出/不抛出异常 - 为什么这不是一个好主意?

c# - 有没有办法只将特定的 C# 属性标记为可序列化?

C# : extract/retrieve child node from JSON structure

javascript - ASP.NET 中的 CheckboxList 选中和取消选中

c# - 创建新库或项目时如何设置命名空间?

c# - 在 XAML 中将数据绑定(bind)到 TreeView

c# - 'Newtonsoft.Json.Linq.JArray' 不包含定义

c# - 当 JsonConstructor 参数名称与 JSON 不匹配时如何抛出异常?

c# - 在 C# 中将 JSON 列表解析为 int 数组