JSON 补丁“替换”整个字符串列表

时间:2021-02-08 02:20:41

标签: c# json .net json-patch

我在使用 JSON Patch 执行更新时遇到问题。在这种情况下,我试图替换整个字符串集合(“名称”)。

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

请求对象:

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

错误(从 ApplyTo 行抛出):

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

该错误非常普遍,我认为请求对象还不错。关于如何替换整个集合的任何想法?

1 个答案:

答案 0 :(得分:0)

您没有设置访问器。

[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>();
}

结果: enter image description here