在JSON文件中找到节点,更新内容,然后使用c#

时间:2018-08-02 05:33:32

标签: c# json linq json.net

当前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;

}

1 个答案:

答案 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);
}