如何使用 newtonsoft.Json 序列化和反序列化多个对象进出列表

How to use newtonsoft.Json to serialize and deserialize multiple objects into and out of a list

所以我正在通过创建一个非常简单的 Register 来练习使用 newtonsoft.Json。

在此代码中,用户输入名字和姓氏,并将其放入我非常简单的 Person 对象中,然后将其放入 List

用户可以添加多人,他们被放入列表

我的代码不工作,我需要帮助,因为我正在学习。

它不起作用,因为我认为序列化和反序列化过程编码错误。

在代码的开头,使用 json 文件中的人员声明了一个列表

List<Person> AllPeopleAdded = new List<Person>(JsonConvert.DeserializeObject<List<Person>>(File.ReadAllText(jsonfilePath)));

这是显示如何将人员添加到 json 文件的代码

File.AppendAllText(jsonfilePath,JsonConvert.SerializeObject(PeopleAddedThisTime));

这是完整代码

using System;
using System.Collections.Generic;
using System.IO;
using OOP__Data_Entry__homework.Classes.Person;
using Newtonsoft.Json;
namespace OOP__Data_Entry__homework
{
    class Program
    {
        const string FirstNameText = "Enter A First Name";
        const string LastNameText = "Enter A Last Name";
        const string ContinueText = "Would you Like to Add Another Person, Yes or No";
        const string YesResponse = "Yes";
        const string NoResponse = "No";
        const string ContinueErrorText = "Enter Yes or No";
        const string jsonfilePath = @"C:\OOP- Data Entry- homework\PeopleSaved.json";
        static void Main(string[] args)
        {
            //done so that line 29 can work, without swaure brackets there is no list for the List (AllPeopleAdded) to take in
            if(File.Exists(jsonfilePath))
            {
            }
            else
            {
                File.WriteAllText(jsonfilePath,"[]");
            }

            List<Person> AllPeopleAdded = new List<Person>(JsonConvert.DeserializeObject<List<Person>>(File.ReadAllText(jsonfilePath)));
            List<Person> PeopleAddedThisTime = new List<Person>();

            //done so that the jsonfile(PeopleSaved.json) doesnt error after the new People are added when the user says they do not want to add any more people (line 57)
            if(File.ReadAllText(jsonfilePath).StartsWith("[]"))
            {
                File.WriteAllText(jsonfilePath,"");
            }

            string FirstName;
            string LastName;
            while(true)
            {
                System.Console.WriteLine(FirstNameText);
                FirstName=Console.ReadLine();
                
                System.Console.WriteLine(LastNameText);
                LastName = Console.ReadLine();

                Person newPerson = new Person(FirstName,LastName);
                PeopleAddedThisTime.Add(newPerson);

                System.Console.WriteLine(ContinueText);
                while(true)
                {
                    string response = Console.ReadLine();
                    if (response==YesResponse)
                    {
                        break;
                    }
                    else if (response == NoResponse)
                    {
                        File.AppendAllText(jsonfilePath,JsonConvert.SerializeObject(PeopleAddedThisTime));
                        foreach(Person allPersons in AllPeopleAdded)
                        {
                            System.Console.WriteLine($"\n {allPersons.GetFullName()}");
                        }
                        foreach(Person newPersons in PeopleAddedThisTime)
                        {
                            System.Console.WriteLine($"\n {newPersons.GetFullName()}");
                        }
                        return;
                    }
                    else
                    {
                        System.Console.WriteLine(ContinueErrorText);
                    }
                }
            }
        }
    }
}

这是代码运行一次后的json文件

[{"mFirstName":"john ","mLastName":"doe"},{"mFirstName":"Josh","mLastName":"Smith"}]

这是代码再次运行后的json文件 (格式不对-这是个问题)

[{"mFirstName":"john ","mLastName":"doe"},{"mFirstName":"Josh","mLastName":"Smith"}][{"mFirstName":"Serge","mLastName":"Superhero"}]

那个人Class

using System;

namespace OOP__Data_Entry__homework.Classes.Person
{
    class Person
    {
        public string mFirstName {get; private set; }
        public string mLastName {get; private set; }

        public Person(string firstName, string lastName)
        {
            mFirstName = firstName;
            mLastName = lastName;
        }
        public string GetFullName()
        {
            return mFirstName+" "+mLastName;
        }
    }
}

json 文件看几次后代码是 运行 使用 serge 的代码

[{"mFirstName":null,"mLastName":null},{"mFirstName":null,"mLastName":null},{"mFirstName":"f","mLastName":"f"}]

您必须将现有 json 反序列化到列表中,将新用户添加到现有用户列表(或者可能删除一些),然后再次序列化整个列表。使用 append 永远行不通,因为 json 总是必须只有一个根元素,并且您必须在该根元素中插入新数据。但是您正在尝试添加第二个根,这会使 json 无效。

    string json = string.Empty;
    using (StreamReader r = new StreamReader(jsonfilePath))
        json = r.ReadToEnd();

 List<Person> AllPeopleAdded = JsonConvert.DeserializeObject<List<Person>>(json);

List<Person> PeopleAddedThisTime = new List<Person>();
    
        
    //.....
    
    AllPeopleAdded.AddRange(PeopleAddedThisTime);

    using (StreamWriter file = File.CreateText(jsonfilePath))
    {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, AllPeopleAdded);
    }

 // or  serialize JSON to a string and then write string to a file
File.WriteAllText(jsonfilePath, JsonConvert.SerializeObject(AllPeopleAdded));

并修正人class

public class Person
{
    public string mFirstName { get; private set; }
    public string mLastName { get; private set; }
    
    [JsonConstructor]
    public Person(string mFirstName, string mLastName)
    {
        this.mFirstName = mFirstName;
        this.mLastName = mLastName;
    }
    public string GetFullName()
    {
        return mFirstName + " " + mLastName;
    }
}