1

Current JSON file looks like this

[ 
 {
    "name": "company xyz",
    "path": "C:\\xxx\\xyz"   
 },   
 {
    "name": "company abc",
    "path": "C:\\xxx\\abc"   
 } 
]

Client Class

public string Name { get; set; }
public string Path { get; set; }

I use the below to pull from the file and display in a combo, this works fine

public static List<Client> GetList()
{
    // Retrieve JSON data from file
    var json = File.ReadAllText(fileName);
    return JsonConvert.DeserializeObject<List<Client>>(json);
}

I would now like to be able to Search for a specific node and Update that content. I have the below code so far which does find the node based on the search string I pass but I'm at a loss at how to now Save the updated node (found) back into the JSON file whilst removing the previous?

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;

}
Tim Cadieux
  • 447
  • 9
  • 21
  • Possible duplicate of [Change values in JSON file (writing files)](https://stackoverflow.com/questions/21695185/change-values-in-json-file-writing-files) – Drag and Drop Aug 02 '18 at 06:41

1 Answers1

3

Try this:

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);
}
Pieter Alberts
  • 829
  • 1
  • 7
  • 23