Home > Blockchain >  Remove object from JSON file c#
Remove object from JSON file c#

Time:02-21

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.

CodePudding user response:

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);

CodePudding user response:

May try something like

result.Person = result.Person.Where(item=> combobox1.Text != $"{item.Name} {item.Sorname}").ToList()

and save the result list in the json file after that

  • Related