10

Based on some value in the request (header or in the url) I want to change the serialization of my DTO objects. Why? Well I've applied the [JsonProperty("A")] to my DTO's but depending on the client (website or mobile app) it want to use that property or not. I started with

services
.AddMvc()
.AddJsonOptions(opt =>
{
#if DEBUG
    opt.SerializerSettings.ContractResolver = new NoJsonPropertyNameContractResolver();
#endif
}

So while debugging I get JSON with full propertynames. I use the JsonProperty attribute to shorten the response JSON, which works fine with the mobile app (Xamarin) which deserialize back to the same DTO's. But now I have a website which uses the the same API to get data via jQuery, but in there I want to deal with the full property names of the DTO's, not the name given in the JsonProperty attribute. Website and WebApi are on the same server so it's no problem if the response is a little bigger.

I started with a middleware class to react on a customer header value, which works, but now I don't know how to get to the JSON SerializerSettings. Searched the web but cannot find it.

While searching I've read about InputFormatters and OutputFormatters, and also content negotiation, but I don't know which direction I must go.

I don't want to deploy the same API twice with different settings.
I'am able to change things like the routesconfig if that would help.

Update
Not only the JSON response had to be serialized in 2 different ways, also the deserializing had to be done in 2 different ways.

3
  • Is there a reason you want to use different property names in the website?
    – Ignas
    Jun 30, 2017 at 14:35
  • 1
    Yes. For the app we used short version of the property names to keep JSON as short as possible. In the app JSON is serialized back to the DTO's, so in code we have full property names. In the website we use jQuery to get/post/put the data, so we want full property names to keep the javascript code readable. I think Input and OutputFormatters are the way to go. Now searching how to init the JsonInputFormatter. Jun 30, 2017 at 14:40
  • How about stackoverflow.com/questions/20622492/… and custom model binder?
    – Ignas
    Jun 30, 2017 at 15:01

2 Answers 2

20

There are at least two serializer-independent ways to do that: passing custom options to JsonResult, and creating a custom response filter. These options are covered below for both Newtonsoft and System.Json libraries.

1. Configuring JsonResult

Create/modify a settings instance (only its type is library-dependent) and pass it into JsonResult constructor. Global JSON settings to modify can be obtained via DI by injecting IOptions<JsonOptions>.

Newtonsoft:

public IActionResult Foo()
{
    var settings = new JsonSerializerSettings
    {
        ContractResolver = new NoJsonPropertyNameContractResolver()
    };

    return new JsonResult(new FooApiModel(), settings);
}

System.Json:

public IActionResult Foo()
{
    var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);

    return new JsonResult(new FooApiModel(), options);
}

2. Adding a result filter

Same idea: just create a new JsonResult with a library-dependent settings instance, so I show only Newtonsoft version for short:

public class ModifyResultFilter : IAsyncResultFilter
{
    public async Task OnResultExecutionAsync(
        ResultExecutingContext context,
        ResultExecutionDelegate next)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new NoJsonPropertyNameContractResolver()
        };

        var originResult = context.Result as JsonResult;

        context.Result = new JsonResult(originResult.Value, settings);

        await next();
    }
}

A filter has to be registered in DI:

builder.Services.AddScoped<ModifyResultFilter>();

Finally, let's use it on an action/controller:

[ServiceFilter(typeof(ModifyResultFilter))]
public IActionResult Index() {}

More about different filters in documentation.

7
  • Thanks, but that would mean changing all controllers (although it aren't that many yet) Jul 3, 2017 at 9:54
  • @ArieKanarie, I thougth twice and added the result filter, so the only change could be to mark a controller with the attribute. Jul 3, 2017 at 10:48
  • Hmm, this could also be a solution. If I'm not mistaken we could access the headers via the context property and depending on the header value we could use different settings. Perhaps this was less work then the solution I came up with. Will think of which one I accept as answer Jul 3, 2017 at 11:11
  • 1
    If you only need to change the output then I would recommend this one instead of my answer. Will be less work. Jul 4, 2017 at 9:33
  • 1
    I think from .net core 6.0, we need to use IOptions<JsonOptions>instead of IOptions<MvcJsonOptions> as MvcJsonOptions is removed from .net core 3.0
    – Jay Shah
    Jul 28, 2022 at 1:36
3

Thanks for the comments and answers. I found a solution with Input and outputformatters. With thanks to http://rovani.net/Explicit-Model-Constructor/ to point me in the right direction.

I've created my own input and outputformatters, which inherit from JsonInputFormatter to keep as much functionality the same.
In the constructor I set the supported mediatype (used some that looks like the existing one for JSON).
Also must override CreateJsonSerializer to set the ContractResolver to the desired one (could implement singleton).
Must do it this way, because changing the serializerSettings in the constructor would change the serializersettings for all input/outputformatters, meaning the default JSON formatters will also use the new contract resolver.
Also doing it this way means you can setup some default JSON options via AddMvc().AddJsonOption()

Example inputformatter, outputformatter uses the same principle:

static MediaTypeHeaderValue protoMediaType = MediaTypeHeaderValue.Parse("application/jsonfull");

public JsonFullInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider) 
    : base(logger, serializerSettings, charPool, objectPoolProvider)
{
    this.SupportedMediaTypes.Clear();
    this.SupportedMediaTypes.Add(protoMediaType);
}

protected override JsonSerializer CreateJsonSerializer()
{
    var serializer = base.CreateJsonSerializer();            
    serializer.ContractResolver = new NoJsonPropertyNameContractResolver();

    return serializer;
}

As per the mentioned URL above the setup class:

public class YourMvcOptionsSetup : IConfigureOptions<MvcOptions>
{
    private readonly ILoggerFactory _loggerFactory;
    private readonly JsonSerializerSettings _jsonSerializerSettings;
    private readonly ArrayPool<char> _charPool;
    private readonly ObjectPoolProvider _objectPoolProvider;

    public YourMvcOptionsSetup(ILoggerFactory loggerFactory, IOptions<MvcJsonOptions> jsonOptions, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider)
    {
        //Validate parameters and set fields
    }

    public void Configure(MvcOptions options)
    {
        var jsonFullInputFormatter = new JsonFullInputFormatter(
            _loggerFactory.CreateLogger<JsonFullInputFormatter>(),
            _jsonSerializerSettings,
            _charPool,
            _objectPoolProvider
        );

        options.InputFormatters.Add(jsonFullInputFormatter);

        options.OutputFormatters.Add(new JsonFullOutputFormatter(
            _jsonSerializerSettings,
            _charPool
        ));
    }

And then an extension method to register it:

public static class MvcBuilderExtensions
{
    public static IMvcBuilder AddJsonFullFormatters(this IMvcBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }
        ServiceDescriptor descriptor = ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, YourMvcOptionsSetup>();
        builder.Services.TryAddEnumerable(descriptor);
        return builder;
    }
}

Call it in ConfigureServices:

services.AddMvc(config =>
{
    config.RespectBrowserAcceptHeader = true; // To use the JsonFullFormatters if clients asks about it via Accept Header
})
.AddJsonFullFormatters() //Add our own JSON Formatters
.AddJsonOptions(opt =>
{
     //Set up some default options all JSON formatters must use (if any)
});

Now our Xamarin App can access the webapi and receive JSON with (short) property names set via JsonProperty attribute.
And in the website we can get the full JSON property names by adding an Accept (get calls) and ContentType (post/put calls) header. Which we do once via jQuery's $.ajaxSetup(.

$.ajaxSetup({
    contentType: "application/jsonfull; charset=utf-8",
    headers: { 'Accept': 'application/jsonfull' }
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.