In .NET 6 there are basically two ways of working with JSON DOM:
more informations about this can be found here
I'm asking myself if it is possible to convert from an instance of JsonDocument to an instance of JsonNode and vice-versa. Basically I'm looking for something like this:
using System.Text.Json;
using System.Text.Json.Nodes;
const string jsonText = "{\"name\": \"Bob\"}";
var jsonNode = JsonNode.Parse(jsonText);
// This code doesn't compile. This is just an example to illustrate what I'm looking for
JsonDocument jsonDocument = jsonNode!.ToJsonDocument();
Just to add a little more context, I'm asking myself this question because JsonDocument has the advantage of being immutable, while JsonNode offers a way to mutate the piece of JSON DOM.
I like working with immutable objects as far as possible, but at the same time I have the need of mutating the JSON DOM I'm working with. A possible strategy to do this could be the following:
JsonDocument from a string (or whatever source for JSON)JsonDocument instance all the way through the codeJsonNode from the JsonDocument instance, perform all the mutations and then get a new immutable instance of JsonDocument. This can be incapsulated inside a private method in charge of doing all the mutationsJsonDocument instanceI haven't found any clue indicating this is possible in the official documentation, so probably this is not possible and these classes have not been designed to work this way.
You can use Deserialize to convert between the two:
const string jsonText = "{\"name\": \"Bob\", \"inner\": {\"names\": [\"Bob\"]}}";
var jsonNode = JsonNode.Parse(jsonText);
using var deserializeDoc = jsonNode.Deserialize<JsonDocument>();
var deserializeNode = deserializeDoc.Deserialize<JsonNode>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With