In .NET 6 there are basically two ways of working with JSON DOM:
- using an immutable JSON DOM via the JsonDocument class
- using a mutable JSON DOM via the JsonNode class
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:
- get an instance of
JsonDocument
from a string (or whatever source for JSON) - work with the immutable
JsonDocument
instance all the way through the code - get an instance of
JsonNode
from theJsonDocument
instance, perform all the mutations and then get a new immutable instance ofJsonDocument
. This can be incapsulated inside a private method in charge of doing all the mutations - keep on working with the new
JsonDocument
instance
I 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.