O.O
O.O

Reputation: 11317

How to pass a JsonPatchDocument as a property in posting object?

Want to post a collection of objects where the objects have a JsonPatchDocument as a property inside it like the below code. However, is this supported or why is the error occurring?

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

Trying to POST with swagger/curl and get

{
  "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"
}

Trying the following combinations and both fail with the above:

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

Upvotes: 3

Views: 1646

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93233

The JSON representation for a JsonPatchDocument is a collection of objects, rather than a single object. In your case, there's only a single change object, but it still must be wrapped as a collection. The second example is closest to what's needed, which I've included here with the change:

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

Upvotes: 3

Related Questions