Search code examples
c#json.netjson-patch

JSON Patch 'replace' entire list of strings


I am having trouble performing an update using JSON Patch. In this case, I am trying to replace the entire collection of strings ('Names').

public class NamesUpdate
{
    public List<string> Names { get; } = new List<string>();
}
public void ReplaceNames([FromBody] JsonPatchDocument<NamesUpdate> namesUpdate)
{
    var newNames = new NamesUpdate();
    namesUpdate.ApplyTo(newNames);
}

Request object:

[
    {
      "op": "replace",
      "path": "/names/",
      "value": ["Ben", "James"]
    }
]

Error (thrown from the ApplyTo line):

Microsoft.AspNetCore.JsonPatch.Exceptions.JsonPatchException: The property at path 'names' could not be updated.

The error is pretty generic and the request object looks okay to me. Any idea on how I can replace the entire collection?


Solution

  • You don't have a set accessor.

    [HttpPatch]
    public IActionResult ReplaceNames([FromBody] JsonPatchDocument<NamesUpdate> namesUpdate)
    {
        var newNames = new NamesUpdate();
        namesUpdate.ApplyTo(newNames);            
        return Ok(newNames);
    }
    public class NamesUpdate
    {
       public List<string> Names { get; set; } = new List<string>();
    }
    

    Result: enter image description here