转换 C# 字符串中的 json 个对象

Converting json objects in c# strings

我有这个

[
    {"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 对象数组),我想为文件提取值对(如类型:"knife")并使它们成为 C# 字符串,所以我可以在我正在进行的一个项目中使用它们!但我无法让它工作,我尝试了很多东西!

有人可以帮我吗?

由于您正在处理具有不同属性的对象(即枪支和刀具)的多重差异 类,您可以考虑将它们序列化为 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 以及您在下方提供的输出示例: