我有持有像數據的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