在c#字符串中转换json对象

时间:2016-05-05 16:12:03

标签: c# json-deserialization package.json

我有这个

[
    {"type":"knife","knifeNO":"1","knifeName":"Shadow Daggers | Crimson Web","knifeEx":"Field Tested","knifeFv":" 0.3297","price":"42 keys","inspect":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198041444572A6024013354D17188164719027219402"},
    {"type":"knife","knifeNO":"2","knifeName":"Shadow Daggers | Urban Masked","knifeEx":"Field Tested","knifeFv":" 0.1972","price":"free","inspect":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198033359234A6046089123D2785026076714870254"}, 
    {"type":"gun","gunNo":"1","gunName":"StatTrak™ P90 | Trigon","gunEx":"Battle-Scarred","gunFv":"0.7393","price":"free","inspect":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198033359234A6042004711D7065101632830923871"},
    {"type":"gun","gunNo":"2","gunName":"M4A1-S | Atomic Alloy","gunEx":"Minimal Wear","gunFv":"0.1102","price":"2 keys","inspect":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198041444572A5899345580D13988253999937991086"}  
]

.json文件(json对象数组),我想为文件提取值对(比如type:" knife")并将它们作为C#字符串,这样我就可以在一个项目中使用它们了我正在努力!但我无法使它工作,我尝试了很多东西!

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

由于您正在处理具有不同属性的多个不同类别的对象(即枪支和刀具),您可以考虑将它们序列化为dynamic个对象,并通过DeserializeObject<T>()方法以这种方式使用它们作者:JSON.NET:

using Newtonsoft.Json;

// Example of your JSON Input
var input = "{your-huge-array-here}";   
// Serialized weapons
var weapons = JsonConvert.DeserializeObject<dynamic[]>(input);
// Go through each type as expected
foreach(dynamic gun in weapons.Where(w => w.type == "gun"))
{
    Console.WriteLine("Gun Number: {0}, Gun Name: {1}",gun.gunNo,gun.gunName);
}
foreach(dynamic knife in weapons.Where(w => w.type == "knife"))
{
    Console.WriteLine("Knife Number: {0}, Knife Name: {1}",knife.knifeNO,knife.knifeName);
}

根据您的需要,您可以更改foreach循环的内容以实际填充字符串,构建您自己的自定义类等。

示例

您可以see a very basic demonstration of this here以及您在下面提供的输出示例:

enter image description here