I am trying to add an element to a JSON array using Microsoft's JsonPatch implementation in .NET 6:
JSON input:
{ "foo": [ 1 ] }
Expected JSON output:
{ "foo": [ 1, 2 ] }
Following their documentation, I ended up with the following code:
string input = @"{ ""foo"": [ 1 ] }";
dynamic obj = JsonSerializer.Deserialize<ExpandoObject>(input);
var patch = new JsonPatchDocument();
patch.Add("/foo/-", 2);
string output = JsonSerializer.Serialize(obj);
Console.WriteLine(output); // throws JsonPatchException, expected { "foo": [ 1, 2 ] }
I expect the foo
property of my object to contain an array equal to [1, 2]
, but instead it fails with the following error:
Microsoft.AspNetCore.JsonPatch.Exceptions.JsonPatchException: The target location specified by path segment '-' was not found.
A Replace
operation on the foo
property successfully updates the ExpandoObject
, but the Add
operation fails. Am I missing something obvious?
I also tried using JsonNode
instead of ExpandoObject
to no avail (JsonNode obj = JsonSerializer.Deserialize<JsonNode>(input);
). The code throws the same error.