Home > Back-end >  Change value in json, when other value is looking for
Change value in json, when other value is looking for

Time:02-16

I have Json where i have 2 objects. I would like to know how to change value in my json, when other value is looking for. For example i would like to change "speciality" to "Warrior" for Person who's "Name" is Harry. It's my Json

{
  "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": [
        "Run",
        "Push",
      ]
    }
  ]
}

My classes

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> People { get; set; }
    public List<Monster> Monsters { get; set; }
}

I tried something like this:

var result = JsonSerializer.Deserialize<Root>(jsonfile)
for (int i = 0; i < result.People.Count;   i)
{
    result.Where(w => w.Person.Name == "Harry").ToList().ForEach(s => s.Person.Speciality = "Warrior");
}

Thanks in advance for some help.

CodePudding user response:

Your can use foreach loop

var result = JsonSerializer.Deserialize<Root>(jsonfile);
foreach (var person in result.Person)
{
  if(person.Name == "Harry"){
     person.Speciality = "";
  }
}
  • Related