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

Change value in json, when other value is looking for

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:

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

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.

>Solution :

Your can use foreach loop

var result = JsonSerializer.Deserialize<Root>(jsonfile);
foreach (var person in result.Person)
{
  if(person.Name == "Harry"){
     person.Speciality = "";
  }
}
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