如何在json文本文件中插入数据



我需要在文本文件中插入一段新数据。这是我用来读取文本文件的方法:

try
{
var path = @"text file\GetAllEmp.txt";

string rawJson = File.ReadAllText(path, Encoding.UTF8);
ObservableCollection<EmployeeItem> Employee = new ObservableCollection<EmployeeItem>();
var jsonData = JsonConvert.SerializeObject(rawJson);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
listitem.ItemsSource = emp;

我只需要在文本文件中添加新的数据。如何添加数据?我试过的是:

public static void Writeemployee()
{
var path = @"text file\GetAllEmp.txt";
string rawJson = File.ReadAllText(path);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
var abs = emp;
for (int i = 0; i < abs.Count; i++)
{
EmployeeItem s_Item = new EmployeeItem();
int SID = ((int)s_Item.SiteID);
DataAccess.AddEmployee(s_Item);
}
}

My data access:

public static async void AddEmployeee(EmployeeItem Employee)
{
}

我只是不知道如何插入。如果有其他方法可以插入,请告诉我。

在UWP中使用文件api不能向Json文件中添加项目,而不删除原始项目。

由于Json文件的格式,项目需要放在[{items1},{items2 }]中,因此需要读取所有项目,然后添加新元素,将列表转换为Json格式并写入文件。

下面是一个代码示例。

EmployeeItem employeeItem = new EmployeeItem
{
Id = 8, 
GroupID = 18,
SiteID = 5565
};
StorageFolder appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
string path = @"GetAllEmp.txt";
//get data
string rawJson = File.ReadAllText(path, Encoding.UTF8);
ObservableCollection<EmployeeItem> Employee = new ObservableCollection<EmployeeItem>();
var jsonData = JsonConvert.SerializeObject(rawJson);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);

emp.Add(employeeItem);
StorageFile sampleFile = await appFolder.GetFileAsync(path);         
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, JsonConvert.SerializeObject(emp));