Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove object from JSON file c#

I want to remove object from json after select from combobox and click button. For example i selected Harry Thomas from combobox and after click on the button Person Harry Thomas should be removed. I have problem with remove object from json only. I tried something like this:

for (int i = 0; i < result.Person.Count; ++i)
{
    if (combobox1.Text == result.Person[i].Name + " " + result.Person[i].Surname)
    {
        result.Person[i].Remove();
    }
}

Json and classes:

{
  "Person": [
    {
      "Speciality": "Archer",
      "Id": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "Id": 432534,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
      ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
      "Name": "Geot",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    }
  ]
}

public class Person
{
    public string Speciality { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> Person { get; set; }
    public List<Monster> Monster { get; set; }
}

How to remove object from json file?
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try this

var result =JsonConvert.DeserializeObject<Root>(json);

var name="Harry"; // replace with combobox
var surname="Thomas"; // replace with combobox
result.Person.RemoveAll(i=>  i.Name==name && i.Surname==surname);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading