使用 json.net 将 JSON 字符串反序列化为对象
我正在构建一个小型应用程序,该应用程序从我无法控制的 API 中提取统计信息。 JSON 字符串如下所示:
{
"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
},
}
]
}
我的对象设置如下:
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; }
}
按照现在设置的方式反序列化字符串没有任何问题,即我可以执行以下操作:
WeapsCollection weps = JsonConvert.DeserializeObject<WeapsCollection>(json);
Console.WriteLine(weps.Weapons.First().AEK.Name.ToString());
Console.ReadLine();
这输出 AEK-971 Vintovka
很好...但我不希望不同的武器作为单独的属性。我希望能够枚举并在每种武器上进行 foreach 或类似的操作:
Console.WriteLine(weapons.Where(w => w.Kills > 30).Name.ToString());
有什么技巧可以实现这一点吗?
实际武器列表有 60 多种,但我一直在考虑在反序列化之前对 JSON 数据执行 string.Replace ("[weaponName]", "weapon") ,但我也无法让它工作。
我将不胜感激任何提示。
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 separate 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以做的就是从 JSON 中删除方括号,这会将其从数组转换为字典。然后,这将直接反序列化到此类中:
然后您可以用它做任何您想做的事情。
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:
You can then do whatever you want with that.