gpt4 book ai didi

C# 使用 JSON 进行序列化

转载 作者:行者123 更新时间:2023-12-02 09:07:14 26 4
gpt4 key购买 nike

我有以下类(class):

public class Employee 
{
public string Name { get; set; }
public int Age{ get; set; }

public Employee(string name, int age)
{
Name = name;
Age = age;
}

public override string ToString()
{
return string.Format("{0},{1}", Name, Age);
}
}

现在在另一个类中我想编写一个 .json 文件来序列化 Employee 类

public class WriteFile
{
public void WriteInFile(List<Employee> list)
{
string filePath="File.json";

var serializer = JsonSerializer.Create();

using (var w = new StreamWriter(filePath)
{

using (JsonTextWriter writer = new JsonTextWriter(w))
{
foreach (Employee item in list)
{

string s = JsonConvert.SerializeObject(item, Formatting.Indented);
serializer.Serialize(writer, s);

}
}

w.Close();
}
}
}

在程序类中

class Program
{

private static void Main(string[] args)
{

List<Employee> listOfEmployees = new List<Employee>();
listOfEmployees.Add(new Employee("Susan", 34 ));
listOfEmployees.Add(new Employee("Jack", 50));
listOfEmployees.Add(new Employee("Sally", 25));


WriteFile write = new WriteFile();
write.WriteInFile(listOfEmployees);

}
}

输出为:

"{\r\n  \"Name\": \"Susan\",\r\n  \"Age\": 34\r\n}""{\r\n  \"Name\": \"Jack\",\r\n  \"Age\": 50\r\n}""{\r\n  \"Name\": \"Sally\",\r\n  \"Age\": 25\r\n}"

格式似乎无法正常工作。我希望将每个姓名和年龄都放在一个新行中,例如:

"Name": "Susan", "Age": 34 

等等。这可能吗?

最佳答案

JSON 仅支持一个顶级对象或数组(请参阅下面的 JSON 语法链接)。要序列化集合,请序列化集合本身。这将创建一个包含元素的有效 JSON 数组。

public async Task WriteInFileAsync(IEnumerable<Employee> employees)
{
var json = JsonConvert.SerializeObject(employees, Formatting.Indented);
await File.WriteAllTextAsync("employees.json", json);
}

JSON grammar from json.org

关于C# 使用 JSON 进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com