Search code examples
c#json.net

Download values of list from json file


I have simple class

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public List<string> ParentsNames { get; set; }
}

And a json file

[
  {
    "Name": "Frank",
    "Surname": "Wilson",
    "Age": "52",
    "Login": "fwillock",
    "Password": "willock123",
    "ParentsNames": [
      "Charles",
      "Sarah"
    ]
  },
  { 
    "Name": "Karen",
    "Surname": "Davies",
    "Age": "35",
    "Login": "kdavies",
    "Password": "davies123",
    "ParentsNames": [
      "Jason",
      "Angela"
    ]
  }
]

I need to get in console all names or surnames, existing in Person list. I tried to use something like this:

var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());

But i don't have any idea to use it in my code. Thanks in advance.


Solution

  • list of names

    var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
    

    to print

    foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");