所以我正在通過創建一個非常簡單的暫存器來練習使用 newtonsoft.Json。
在這段代碼中,用戶輸入名字和姓氏,然后將其放入我非常簡單的 Person 物件中,然后將其放入 List
用戶可以添加多個人并將他們放入串列中
我的代碼不起作用,我需要幫助,因為我正在學習。
它不起作用,因為我認為序列化和反序列化程序編碼錯誤。
在代碼的開頭,使用 json 檔案中的 People 宣告了一個 List
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"}]
人員類
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;
}
}
}
使用 serge 的代碼運行代碼幾次后,json 檔案的外觀
[{"mFirstName":null,"mLastName":null},{"mFirstName":null,"mLastName":null},{"mFirstName":"f","mLastName":"f"}]
uj5u.com熱心網友回復:
您必須將現有 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));
并修復人員類
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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425656.html
