На этом этапе кода я работал с JsonDocument и определил новый JsonElement, который необходимо добавить в исправление.
В RFC приведены два примера документов и их исправление JSON:
Код: Выделить всё
Start: { "foo": "bar" }
Patch: [{ "op": "add", "path": "/child", "value": { "grandchild": { } } }]
End: {"foo": "bar","child": {"grandchild": { } } }
Код: Выделить всё
using System.Text.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.JsonPatch;
// JsonElement element is the change we want to see added in the patch
JsonPatchDocument patchDocument = new JsonPatchDocument();
patchDocument.Add(path, element); // Only the JsonElement property comes through. Gives [{"value":{"ValueKind":1},"path":"/child","op":"add"}]
patchDocument.Add(path, element.GetRawText()); // Obviously treated as a string so fails and gives [{"value":"{\n \"grandchild\": {\n }\n }","path":"/child","op":"add"}]
patchDocument.Add(path, element.GetString()); // Similar to the above attempt, but fails because element is an Object and throws exception. Attempting to replicate Newtonsoft's ToObject gives the next example
patchDocument.Add(path, netjson.JsonSerializer.Deserialize(element.GetRawText())); // Just a more convoluted version of our first attempt. Gives [{"value":{"ValueKind":1},"path":"/child","op":"add"}]
Код: Выделить всё
JsonPatchDocument patchDocument = new JsonPatchDocument();
JsonDocument newDocument = JsonDocument.Parse("{ \"foo\": \"bar\", \"child\": {\"grandchild\": { } } }");
JsonElement parentObject = newDocument.RootElement;
JsonElement element = parentObject.GetProperty("child");
// This is more dynamic in real code, but hardcoded for example
patchDocument.Add("/", JObject.Parse(parentObject.GetRawText()).Property("child").Value); // Correct answer [{\"value\":{\"grandchild\":{}},\"path\":\"/\",\"op\":\"add\"}]
Подробнее здесь: https://stackoverflow.com/questions/663 ... chdocument
Мобильная версия