我有持有像数据的JSON文件:如何根据C#中的条件删除一组Json对象?
[
{
"applicationName": "ABC",
"machineName": "XYZ",
"OrderNumber": "N46464646"
},
{
"applicationName": "DEF",
"machineName": "XYZ",
"OrderNumber": "D46364636"
},
{
"applicationName": "ABC",
"machineName": "XYZ",
"OrderNumber": "D34343434"
}
]
我想从基于订单编号例如上述数据中移除一组对象的:如果我给订单编号“D46364636”,它应该删除 -
{
"applicationName": "DEF",
"machineName": "XYZ",
"OrderNumber": "D46364636"
}
我已经尝试过做这样这个 -
JsonDataList = new List<JsonItem>();
string input = "";
string inputApplicationName = "";
string inputMachineName = "";
string inputOrderNum = "";
while (input != "q")
{
Console.WriteLine("Press 'd' to Delete item");
Console.WriteLine("Press 'q' to Quit Program");
Console.WriteLine("Press Command:");
input = Console.ReadLine();
switch (input)
{
case "d":
Console.WriteLine("Enter Order Number to remove:");
inputOrderNum = Console.ReadLine();
var js = File.ReadAllText(@"C:\Users\ab54253\Documents\visual studio 2010\Projects\JSONExample\JSONExample\JsonData\AutomatedJson.json");
var result=JsonConvert.DeserializeObject<List<JsonData>>(js);
foreach(var item in result)
{
if(item.OrderNumber==inputOrderNum)
{
JsonDataList.Remove(new JsonItem(item.applicationName, item.machineName, item.OrderNumber));
}
}
break;
case "q":
Console.WriteLine("Quit Program");
break;
default:
Console.WriteLine("Incorrect Command, Try Again");
break;
}
}
Console.WriteLine("Rewriting AutomatedJson.json");
string JD = JsonConvert.SerializeObject(JsonDataList, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(@"C:\Users\ab54253\Documents\visual studio 2010\Projects\JSONExample\JSONExample\JsonData\AutomatedJson.json", JD);
Console.ReadLine();
我能够检查与条件,我曾经用删除的数据:
if(item.OrderNumber==inputOrderNum)
{
JsonDataList.Remove(new JsonItem(item.applicationName, item.machineName, item.OrderNumber));
}
通过使用上面的一段代码,它将从JSON文件中删除所有数据,而不是删除所需的数据。请指导我。
您还没有填充'JsonDataList'。所以,'Remove'行不会删除任何东西,因为列表已经是空的。您可以将'var result = ...'行更改为'JsonDataList = ...'。然而,Rajnik Patel的饮料更简洁。 – HebeleHododo