We should be able serialize and deserialize from DOM
Consider this coding snippet of JSON.NET outlined by @robertmclaws:
public async Task<bool> SomeMethod([FromBody] JObject data)
{
var model = data.ToObject<SomeObject>();
}
Today, you can't do this with System.Text.Json. I propose we add APIs so that you can write this:
public async Task<bool> SomeMethod([FromBody] JsonElement data)
{
var model = data.Deserialize<SomeObject>();
}
API Proposal
namespace System.Text.Json
{
public static partial class JsonSerializer
{
+ public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null);
+ public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null);
+ public static TValue? Deserialize<TValue>(this JsonDocument document, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context);
+ public static JsonDocument SerializeToDocument<TValue>(TValue value, JsonSerializerOptions? options = null);
+ public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerOptions? options = null);
+ public static JsonDocument SerializeToDocument<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context);
+ public static TValue? Deserialize<TValue>(this JsonElement element, JsonSerializerOptions? options = null);
+ public static TValue? Deserialize<TValue>(this JsonElement element, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null);
+ public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context);
+ public static JsonElement SerializeToElement<TValue>(TValue value, JsonSerializerOptions? options = null);
+ public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerOptions? options = null);
+ public static JsonElement SerializeToElement<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context);
+ public static TValue? Deserialize<TValue>(this JsonNode node, JsonSerializerOptions? options = null);
+ public static TValue? Deserialize<TValue>(this JsonNode node, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static object? Deserialize(this JsonNode node, Type returnType, JsonSerializerOptions? options = null);
+ public static object? Deserialize(this JsonNode node, Type returnType, JsonSerializerContext context);
+ public static JsonNode? SerializeToNode<TValue>(TValue value, JsonSerializerOptions? options = null);
+ public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerOptions? options = null);
+ public static JsonNode? SerializeToNode<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo);
+ public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context);
}
}
Might be a dup of https://github.com/dotnet/corefx/issues/37564
Is it possible to add the following to the API proposal?
public static JsonElement SerializeToElement
Any progress on this? Just ran into the issue again in one of my projects. Thanks!
I propose to not only have the generics variant, but also one where the Type can be specified as a parameter, so use-cases involving reflection are covered as well. The new API would look like this (Also added the suggestion of @bjornen77):
API Proposal
namespace System.Text.Json
{
public static partial class JsonSerializer
{
public static TValue Deserialize<TValue>(this JsonDocument document);
public static object Deserialize(this JsonDocument document, Type valueType);
public static TValue Deserialize<TValue>(this JsonElement element);
public static object Deserialize(this JsonElement element, Type valueType);
public static JsonDocument SerializeToDocument<TValue>(TValue value);
public static JsonDocument SerializeToDocument(object value, Type valueType);
public static JsonElement SerializeToElement<TValue>(TValue value);
public static JsonElement SerializeToElement(object value, Type valueType);
}
}
There should be an overload that allows us to pass in serializer options, e.g. custom converters.
The proposal should also pass JsonSerializerOptions as an optional parametes in order to pick up any custom converters added at runtime as well as other options such as null handling.
Would also like this feature, currently using the GetRawText() hack.
Would also like this feature, currently using the GetRawText() hack.
what's the GetRawText() hack?
JsonSerializer.Deserialize<SomeObject>(element.GetRawText())
Doing the same hack as described above. Using System.Text.Json in a high throughput/performance system and it is painful having to use this hack.
it would be nice if this had async versions as well
Here is what I'm using in the meantime:
public static class JsonElementExtensions
{
public static async Task<T> ToObjectAsync<T>(this JsonElement element, JsonSerializerOptions options = null,
CancellationToken token = default)
{
var bufferWriter = new ArrayBufferWriter<byte>();
await using var writer = new Utf8JsonWriter(bufferWriter);
element.WriteTo(writer);
// NOTE: call Flush on the writer before Deserializing since Dispose is called at the end of the scope of the method
await writer.FlushAsync(token);
return JsonSerializer.Deserialize<T>(bufferWriter.WrittenSpan, options);
}
public static async Task<T> ToObjectAsync<T>(this JsonDocument document, JsonSerializerOptions options = null,
CancellationToken token = default)
{
if (document == null) throw new ArgumentNullException(nameof(document));
return await document.RootElement.ToObjectAsync<T>(options, token: token);
}
}
@steveharter did this get added with our DOM/dynamic feature or not yet?
These are mostly small extensions; I'll add samples here for now. There are many permutations to consider (to\from object, JsonElement, JsonDocument, JsonNode*) and different programming models to consider (i.e. whether to add to JsonSerializer as static methods, or add as instance methods to JsonElement, JsonNode, etc)
See also https://github.com/dotnet/runtime/issues/54158
Why did this issue get closed in when the problem is not actually solved yet?
@steveharter I assume closing was an accident?
@robertmclaws
Why did this issue get closed in when the problem is not actually solved yet?
I blame GitHub's UX

Updated the API proposal to include JsonDocument, JsonElement and also JsonNode per https://github.com/dotnet/runtime/issues/54158.
Also all 4 permutations were included (generic + options, non-generic + options, generic + context, non-generic + context).
The Deserialize methods are extension methods for document\element\node so they can be used with an instance which may help discoverability:
using JsonDocument dom = JsonDocument.Parse(Json);
// Using the instance
MyPoco obj1 = dom.Deserialize<MyPoco>();
// Using JsonSerializer
MyPoco obj2 = JsonSerializer.Deserialize<MyPoco>(dom);
For V6 there are two choices:
- Add these new APIs (special approval necessary since we are passed the Preview 7 cutoff).
- Show samples on how to add extensions to your own helper class.
Option (2) will not be as performant depending on the permutation:
- The Serialize extensions will perform unnecessary escaping for the temporary JSON needed to bridge between the CLR object and the DOM type. Also
SerializeToDocument()will perform an unnecessary buffer alloc\copy. - The Deserialize for
JsonNodewill perform unnecessary escaping and a buffer alloc\copy.
In theory, the JsonDocument APIs could be removed which would force usage of the JsonElement APIs. However, this has some minor usability concerns:
- For serialize, the
document.RootElementwould need to be called to obtain the root element. - For serialize,
JsonDocumenthas a perf advantage overJsonElementsince the same buffer that is used by the writer (which contains the JSON obtained from the object) can be held byJsonDocument, avoiding an extra alloc\copy; the buffer is returned back to the pool whendocument.Dispose()is called. - For deserialize, existing user methods that take
JsonDocumentwould need to be changed to takeJsonElementsince it is not possible to obtainJsonDocumentfrom aJsonElement.