使用Json.NET

时间:2015-08-26 15:55:57

标签: c# json json.net

我有一些看起来像这样的JSON:

{
    "account_id": 4294967295,
    "player_slot": 0,
    "hero_id": 93,
    "item_0": 170,
    "item_1": 160,
    "item_2": 81,
    "item_3": 208,
    "item_4": 63,
    "item_5": 0,
    "kills": 17,
    "deaths": 6,
    "assists": 8,
    "leaver_status": 0,
    "gold": 2978,
    "last_hits": 80,
    "denies": 0,
    "gold_per_min": 434,
    "xp_per_min": 630,
    "gold_spent": 19090,
    "hero_damage": 16232,
    "tower_damage": 229,
    "hero_healing": 522,
    "level": 25,
    "ability_upgrades": [ <snip> ]
}

我想序列化到我的模型,如下所示:

[JsonConverter(typeof(MatchDetailPlayerConverter))]
public class MatchDetailPlayer
{
    public int AccountId { get; set; }
    public PlayerSlot PlayerSlot { get; set; }
    public Hero Hero { get; set; }
    public List<Item> Items { get; set; }
    public int Kills { get; set; }
    public int Deaths { get; set; }
    public int Assists { get; set; }
    public LeaverStatus LeaverStatus { get; set; }
    public int Gold { get; set; }
    public int LastHits { get; set; }
    public int Denies { get; set; }
    public int GoldPerMin { get; set; }
    public int XpPerMin { get; set; }
    public int GoldSpent { get; set; }
    public int HeroDamage { get; set; }
    public int TowerDamage { get; set; }
    public int HeroHealing { get; set; }
    public int Level { get; set; }
    public List<AbilityUpgrade> AbilityUpgrades { get; set; }
    public List<AdditionalUnit> AdditionalUnits { get; set; }
}

在JSON中有6个名为item_x的属性,它们是项目的ID。我想将这6个键/值反序列化为一个List<Item>。我的item类是一个枚举,它将项ID为值。

我编写了一个可以找到的自定义JsonConverter here。我的问题是转换器在转换器的jo.ToObject<MatchDetailPlayer>()方法中ReadJson()时仍然遇到堆栈溢出。

导致这种无限循环的原因是什么?有没有更好的方法将许多键/值反序列化为单个对象列表?

1 个答案:

答案 0 :(得分:1)

我认为您可以查看类中JsonExtensionData属性的实现来手动修改反序列化 你可以在这里找到一个样本: Json Serialization Attributes