runtime icon indicating copy to clipboard operation
runtime copied to clipboard

We should be able serialize and deserialize from DOM

Open terrajobst opened this issue 7 years ago • 22 comments

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);
    }
}

terrajobst avatar Oct 23 '19 18:10 terrajobst

Might be a dup of https://github.com/dotnet/corefx/issues/37564

ericstj avatar Oct 23 '19 20:10 ericstj

Is it possible to add the following to the API proposal?

public static JsonElement SerializeToElement(TValue value);

bjornen77 avatar Jan 31 '20 13:01 bjornen77

Any progress on this? Just ran into the issue again in one of my projects. Thanks!

robertmclaws avatar Jun 07 '20 20:06 robertmclaws

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);
    }
}

NoRelect avatar Jun 28 '20 21:06 NoRelect

There should be an overload that allows us to pass in serializer options, e.g. custom converters.

cluetjen avatar Sep 29 '20 19:09 cluetjen

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.

steveharter avatar Feb 22 '21 16:02 steveharter

Would also like this feature, currently using the GetRawText() hack.

wizofaus avatar Mar 03 '21 03:03 wizofaus

Would also like this feature, currently using the GetRawText() hack.

what's the GetRawText() hack?

thepirat000 avatar Mar 03 '21 06:03 thepirat000

JsonSerializer.Deserialize<SomeObject>(element.GetRawText())

wizofaus avatar Mar 03 '21 10:03 wizofaus

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.

stonstad avatar Mar 03 '21 21:03 stonstad

it would be nice if this had async versions as well

udlose avatar Mar 22 '21 20:03 udlose

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);
    }
}

udlose avatar Mar 22 '21 20:03 udlose

@steveharter did this get added with our DOM/dynamic feature or not yet?

ericstj avatar Apr 22 '21 23:04 ericstj

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)

steveharter avatar Jul 08 '21 17:07 steveharter

See also https://github.com/dotnet/runtime/issues/54158

steveharter avatar Jul 16 '21 15:07 steveharter

Why did this issue get closed in when the problem is not actually solved yet?

robertmclaws avatar Jul 16 '21 16:07 robertmclaws

@steveharter I assume closing was an accident?

terrajobst avatar Jul 16 '21 20:07 terrajobst

@robertmclaws

Why did this issue get closed in when the problem is not actually solved yet?

I blame GitHub's UX

image

terrajobst avatar Jul 19 '21 16:07 terrajobst

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:

  1. Add these new APIs (special approval necessary since we are passed the Preview 7 cutoff).
  2. 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 JsonNode will perform unnecessary escaping and a buffer alloc\copy.

steveharter avatar Jul 20 '21 13:07 steveharter

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.RootElement would need to be called to obtain the root element.
  • For serialize, JsonDocument has a perf advantage over JsonElement since the same buffer that is used by the writer (which contains the JSON obtained from the object) can be held by JsonDocument, avoiding an extra alloc\copy; the buffer is returned back to the pool when document.Dispose() is called.
  • For deserialize, existing user methods that take JsonDocument would need to be changed to take JsonElement since it is not possible to obtain JsonDocument from a JsonElement.

steveharter avatar Jul 20 '21 14:07 steveharter