Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert between JsonDocument and JsonNode?

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:

  1. get an instance of JsonDocument from a string (or whatever source for JSON)
  2. work with the immutable JsonDocument instance all the way through the code
  3. get an instance of JsonNode 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 mutations
  4. 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.

like image 275
Enrico Massone Avatar asked Feb 24 '26 03:02

Enrico Massone


1 Answers

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>();
like image 60
Guru Stron Avatar answered Feb 26 '26 17:02

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!