aspnet / Mvc

[Archived] ASP.NET Core MVC is a model view controller framework for building dynamic web sites with clean separation of concerns, including the merged MVC, Web API, and Web Pages w/ Razor. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
5.62k stars 2.14k forks source link

[pubinternal] JsonSerializerObjectPolicy #8712

Closed MarcusKohnert closed 5 years ago

MarcusKohnert commented 5 years ago

Description of the problem: #8689

We are using Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonSerializerObjectPolicy because we want to get hold of a JsonSerializer from the ObjectPool.

Use case:

We retrieve a Json-String from a DB and want to serialize it to the client as a string property on an object. But the to-string-serialized-json needs to be in the same format as specified by IOptions<MvcJsonOptions> (DateParseHandling).

Exact code:

SomeRepresentation.cs
public class SomeRepresentation
{
    public SomeRepresentation(JObject attributes)
    {
        this.Attributes = attributes;
    }

    public JObject Attributes { get; }
}
SomeController.cs - in an action method
var jsonSerializerPool = this.objectPoolProvider
                             .Create(new JsonSerializerObjectPolicy(jsonOptions.Value.SerializerSettings));

var jsonSerializer = jsonSerializerPool.Get();

try
{
    using (var stringReader = new StringReader("... some JSON from db ..."))
    using (var reader = new JsonTextReader(stringReader))
    {
        var json = jsonSerializer.Deserialize<JObject>(reader);

        return this.HAL
        (
            new HALResponse
            (
                new SomeRepresentation(json)
            )
            .AddLinks(await this.GetLinks())
        );
    }
}
finally
{
    jsonSerializerPool.Return(jsonSerializer);
}
pranavkm commented 5 years ago

needs to be in the same format as specified by IOptions (DateParseHandling).

You should be able to construct a JsonSerailizer using MvcJsonOptions.SerializerSettings without much ceremony - in fact that's what the policy does: https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.Formatters.Json/Internal/JsonSerializerObjectPolicy.cs#L27.

If you do need to pool your JsonSerializer settings, I'd recommend just copying the type. The fact that the formatter pools the serializer, is an implementation detail and we wouldn't expose it as part of a public API surface.