C#使用JSON序列化

我有以下课程:

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数组。

       public void WriteInFile(IEnumerable<Employee> employees)
       {
           var jsonArray = JsonConvert.SerializeObject(employees);
           File.WriteAllText("employees.json", jsonArray);
       }