neuecc / Utf8Json

Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin).
MIT License
2.36k stars 267 forks source link

Setup of AspNetCoreMvcFormatter #150

Open dylanvdmerwe opened 5 years ago

dylanvdmerwe commented 5 years ago

The docs currently specify this code to setup the Input and Output formatters for Aspnet:

    services.AddMvc().AddMvcOptions(option =>
    {
        option.OutputFormatters.Clear();
        // can pass IJsonFormatterResolver for customize.
        option.OutputFormatters.Add(new JsonOutputFormatter(StandardResolver.Default));
        option.InputFormatters.Clear();
        // if does not pass, library should use JsonSerializer.DefaultResolver.
        option.InputFormatters.Add(new JsonInputFormatter());
    });

However this will cause issues and will make the plugin not drop-in compatible.

You probably want to use something more along the lines of:

            services.AddMvc().AddMvcOptions(options =>
            {
                // remove the existing JSON formatter
                options.OutputFormatters.RemoveType(typeof(JsonOutputFormatter));
                options.InputFormatters.RemoveType(typeof(JsonInputFormatter));

                // add utf8json formatters to handle JSON
                var resolver = CompositeResolver.Create(
                    EnumResolver.UnderlyingValue,
                    StandardResolver.AllowPrivateExcludeNullCamelCase
                );

                options.OutputFormatters.Add(new Utf8Json.AspNetCoreMvcFormatter.JsonOutputFormatter(resolver));
                options.InputFormatters.Add(new Utf8Json.AspNetCoreMvcFormatter.JsonInputFormatter(resolver));

            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);