从 json 文件下载列表值
Download values of list from json file
我有简单的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; }
}
还有一个json文件
[
{
"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"
]
}
]
我需要在控制台中获取人员列表中存在的所有名字或姓氏。我试着用这样的东西:
var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());
但我不知道在我的代码中使用它。
提前致谢。
名单
var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
打印
foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");
如果您想自定义在 class 中显示信息的方式,一种选择是为您的 Person
覆盖 ToString()
class:
class Person
{
...
// customize however you like
public override string ToString() => $"{Name} {Surname}";
}
然后单行显示,可以用string.Join()
:
Console.WriteLine(string.Join(", ", result));
或者如果您希望每个人换行:
result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);
我有简单的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; }
}
还有一个json文件
[
{
"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"
]
}
]
我需要在控制台中获取人员列表中存在的所有名字或姓氏。我试着用这样的东西:
var JsonDeserialize = File.ReadAllText(fileName);
List<Person> result = JsonSerializer.Deserialize<List<Person>>(JsonDeserialize);
Console.WriteLine(result.Select(x => x.Name).ToList());
但我不知道在我的代码中使用它。 提前致谢。
名单
var names= result.Select(i=> new {Name=i.Name, Surname=i.Surname}).ToList();
打印
foreach (var n in result) Console.WriteLine ( $"{n.Name} {n.Surname}");
如果您想自定义在 class 中显示信息的方式,一种选择是为您的 Person
覆盖 ToString()
class:
class Person
{
...
// customize however you like
public override string ToString() => $"{Name} {Surname}";
}
然后单行显示,可以用string.Join()
:
Console.WriteLine(string.Join(", ", result));
或者如果您希望每个人换行:
result.ForEach(person => Console.WriteLine(person));
// which can be shortened to
result.ForEach(Console.WriteLine);