Does deserializing into JsonElement dispose of the parent JsonDocument?

Viewed 53

The documentation encourages us to do this when needed for flexibility reasons:

If you just want to be flexible about what JSON to accept for a particular property, an alternative is to deserialize into JsonElement or JsonNode. Any valid JSON property can be deserialized into JsonElement or JsonNode. Choose JsonElement to create an immutable object or JsonNode to create a mutable object.

Having a JsonElement property obviously handles this correctly. My question is about using JsonSerializer.Deserialize<JsonElement>(someString).

2 Answers

Found my answer.
The devs note that they indeed dispose of the JsonDocument.

If the concern is about using up the array pool and not returning things back, we are cloning the element before returning it (which uses a GC-tracked/regular array) and we are disposing the original document. This returns the original array back to the pool.

Serialize(), Deserialize(), SerializeAsync() do not need to be disposed. Because after the execution of the function, there is no open resources or connection.

Related