如何在发布对象中将JsonPatchDocument作为属性传递?

时间:2020-01-23 20:17:07

标签: c# asp.net-core

想要发布对象的集合,其中对象具有JsonPatchDocument作为其内部的属性,如以下代码所示。但是,这是否受支持,或者为什么会发生错误?

public class Person
{
    public string Name { get; set; }
}

public class DummyClass
{
    public int PriKey { get; set; }
    public JsonPatchDocument<Person> PersonPatchDocument { get; set; }
}

[HttpPost]
public IActionResult Test(IEnumerable<DummyClass> input)
{
    return Ok();
}

尝试用招摇/卷曲进行发布并获取

{
  "errors": {
    "[0].PersonPatchDocument": [
      "The JSON patch document was malformed and could not be parsed."
    ]
  },
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "8000000d-0007-fd00-b63f-84710c7967bb"
}

尝试以下组合,但均无法通过以上方法进行

[
  {
    "PriKey": 1,
    "PersonPatchDocument": {
      "ContractResolver": {
        "value": "bob",
        "path": "/name",
        "op": "replace"
      }
    }
  }
]
[
  {
    "PriKey": 1,
    "PersonPatchDocument": {
      "value": "bob",
      "path": "/name",
      "op": "replace"
    }
  }
]

1 个答案:

答案 0 :(得分:2)

JsonPatchDocument的JSON表示形式是对象的集合,而不是单个对象。在您的情况下,只有一个更改对象,但仍必须将其包装为一个集合。第二个示例最接近所需的示例,我将其包含在更改中:

[
  {
    "PriKey": 1,
    "PersonPatchDocument": [
      {
        "value": "bob",
        "path": "/name",
        "op": "replace"
      }
    ]
  }
]