-1

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.

Maxime Rossini
  • 3,612
  • 4
  • 31
  • 47

1 Answers1

0

In the meantime, as a workaround, I am using JsonPatch.Net. The code looks similar:

string input = @"{ ""foo"": [ 1 ] }";
JsonNode obj = JsonSerializer.Deserialize<JsonNode>(input);
var patch = new JsonPatch(PatchOperation.Add(JsonPointer.Parse("/foo/-"), 2));
PatchResult patchResult = patch.Apply(obj);
string output = JsonSerializer.Serialize(patchResult.Result);
Console.WriteLine(output); // { "foo": [ 1, 2 ] }
Maxime Rossini
  • 3,612
  • 4
  • 31
  • 47