Havunen / SystemTextJsonPatch

SystemTextJsonPatch is a JSON Patch (JsonPatchDocument) RFC 6902 implementation for .NET using System.Text.Json
MIT License
102 stars 12 forks source link

Patch for <object> type #16

Closed AleksandrLiakhavetsEPAM closed 1 year ago

AleksandrLiakhavetsEPAM commented 1 year ago

Does the patch work for the object type? I tried this method but was unsuccessful...

Request:

[
  {"op": "replace", "path": "number", "value": 86632}
]

Handler

[HttpPatch]
public IActionResult Patch([FromBody] JsonPatchDocument patchDoc)
{
      var jsonData = """"
            {
                 "number": 1111
            }
             """";

      var obj = JsonSerializer.Deserialize<object>(jsonData)!;

      patchDoc.ApplyTo(obj);

      return Ok(patchDoc);
}

Exceptions

he target location specified by path segment 'number' was not found.

Havunen commented 1 year ago

Good question, I havent tested this behavior.

Havunen commented 1 year ago

Yeah this doesn't work because System.Text.Json deserializes object as JsonElement type and that type does not have writable setters.

You could however Deserialize jsonData as JsonNode

using System.Text.Json.Nodes;

[HttpPatch]
public IActionResult Patch([FromBody] JsonPatchDocument patchDoc)
{
      var jsonData = """"
            {
                 "number": 1111
            }
             """";

      var obj = JsonSerializer.Deserialize<JsonNode>(jsonData)!;

      patchDoc.ApplyTo(obj);

      return Ok(patchDoc);
}

Maybe that suits your need?

AleksandrLiakhavetsEPAM commented 1 year ago

Thank you for your answer. Will try to with it.