当前JSON文件如下
[
{
"name": "company xyz",
"path": "C:\\xxx\\xyz"
},
{
"name": "company abc",
"path": "C:\\xxx\\abc"
}
]
客户端类
public string Name { get; set; }
public string Path { get; set; }
我使用以下内容从文件中提取并组合显示,这很好
public static List<Client> GetList()
{
// Retrieve JSON data from file
var json = File.ReadAllText(fileName);
return JsonConvert.DeserializeObject<List<Client>>(json);
}
我现在希望能够搜索特定节点并更新该内容。到目前为止,我有以下代码可以根据我通过的搜索字符串找到节点,但是现在我不知如何将已更新的节点(找到的)保存回JSON文件,同时删除先前的节点?
public static void Update(Client c, string s)
{
var json = File.ReadAllText(fileName);
List<Client> list = JsonConvert.DeserializeObject<List<Client>>(json);
Client found = list.Where(x => x.Name == s).Single();
found.Name = c.Name;
found.Path = c.Path;
}
答案 0 :(得分:3)
尝试一下:
public static void Update(Client c, string s)
{
var json = File.ReadAllText(fileName);
List<Client> list = JsonConvert.DeserializeObject<List<Client>>(json);
Client found = list.Where(x => x.Name == s).Single();
found.Name = c.Name;
found.Path = c.Path;
var updatedJson = JsonConvert.SerializeObject(list);
File.WriteAllText(fileName, updatedJson);
}