6

I'm having two controller controllers: ControllerA and ControllerB. The base class of each controller is ControllerBase.

The ControllerA needs to deserialize JSON in the default option

JsonSerializerOptions.IgnoreNullValues = false;

The ControllerB needs to deserialize JSON with option

JsonSerializerOptions.IgnoreNullValues = true;

I know how to set this option global in Startup.cs

services.AddControllers().AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);

But how to set specific deserialize options to Controller or Action? (ASP.NET Core 3 API)

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
Mag
  • 61
  • 1
  • 3
  • 2
    You can try to achieve it with an ActionFilter, and [this SO thread](https://stackoverflow.com/questions/52605946/change-the-json-serialization-settings-of-a-single-asp-net-core-controller) discussed a similar requirement, you can refer to it. – Fei Han Feb 04 '20 at 07:52
  • Does this answer your question? [Change the JSON serialization settings of a single ASP.NET Core controller](https://stackoverflow.com/questions/52605946/change-the-json-serialization-settings-of-a-single-asp-net-core-controller) – Ian Kemp Oct 05 '20 at 14:25

1 Answers1

1

As suggested by Fei Han, the straight-forward answer is to use on ControllerB the attribute NullValuesJsonOutput :

public class NullValuesJsonOutputAttribute : ActionFilterAttribute
{
    private static readonly SystemTextJsonOutputFormatter Formatter = new SystemTextJsonOutputFormatter(new JsonSerializerOptions
    {
        IgnoreNullValues = true
    });

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
            objectResult.Formatters.Add(Formatter);
    }
}
McX
  • 1,296
  • 2
  • 12
  • 16
  • You might want to post this answer on the question I've linked as a duplicate, as this question is likely to get closed. – Ian Kemp Oct 05 '20 at 14:27
  • @IanKemp There's already a good answer on the duplicate (also pointed by Fei Han), which I adapted for this question. – McX Oct 07 '20 at 07:34