I have a Json file which holds data like:
[
{
"applicationName": "ABC",
"machineName": "XYZ",
"OrderNumber": "N46464646"
},
{
"applicationName": "DEF",
"machineName": "XYZ",
"OrderNumber": "D46364636"
},
{
"applicationName": "ABC",
"machineName": "XYZ",
"OrderNumber": "D34343434"
}
]
I want to remove a set of object from the above data based on Order Number for eg: If I give order number "D46364636", it should remove-
{
"applicationName": "DEF",
"machineName": "XYZ",
"OrderNumber": "D46364636"
}
I have tried it doing like this-
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();
I am able to check with the condition and I used to remove data by using:
if(item.OrderNumber==inputOrderNum)
{
JsonDataList.Remove(new JsonItem(item.applicationName, item.machineName, item.OrderNumber));
}
By using above piece of code it is removing all the data from the JSON file instead of removing required data.Please guide me.
JsonDataList. So, thatRemoveline is not removing anything, because the list is already empty. You can change thevar result = ...line toJsonDataList = .... However, Rajnik Patel's anwer is more succinct.