开发者

Deserializing JSON string to Object with json.net

I'm building a small application that pulls statistics from an API I have no control over. The JSON string looks like this:

{
    "weapons":
        [
            {
                "aek":
                    {
                        "name":"AEK-971 Vintovka",
                        "kills":47,
                        "shots_fired":5406,
                        "shots_hit":858
                    },
                "xm8":
                    {
                        "name":"XM8 Prototype",
                        "kills":133,
                        "shots_fired":10170,
                        "shots_hit":1790
                    },
            }
        ]
}

and my objects are set up as follows:

class WeapsCollection
{
    public WeaponList[] Weapons { get; set; }
}

class WeaponList
{
    public WeaponDetails AEK { get; set; }
    public WeaponDetails XM8 { get; set; }
}

class WeaponDetails
{
    public string Name { get; set; }
    public int Kills { get; set; }
    public int Shots_Fired { get; set; }
    public int Shots_Hit { get; set; }
}

I don't have any problems deserializing the string the way it is set up now, i.e. I can do:

WeapsCollection weps = JsonConvert.DeserializeObject<WeapsCollection>(json);
Console.WriteLine(weps.Weapons.First().AEK.Name.ToString());
Console.ReadLine();

This outputs AEK-971 Vintovka

Fine... but I don't want the different weapons as separ开发者_Go百科ate properties. I want to be able to enumerate and do a foreach on each weapon or something like this:

Console.WriteLine(weapons.Where(w => w.Kills > 30).Name.ToString());

Any tips how to achieve this?

The list of actual weapons is 60+ but I've been thinking about doing a string.Replace ("[weaponName]", "weapon") on the JSON data before deserializing it, but I cannot get it to work either.

I'd appreciate any tips.


What you could do is remove the square brackets from your JSON, which turns it from an array into a dictionary. This will then deserialise directly into this class:

class WeaponList
{
    public Dictionary<string, WeaponDetails> Weapons { get; set; }
}

You can then do whatever you want with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜