return JSON as is (PascalCase) from one Action

3.4k Views Asked by At

in asp.net core 3 the returned json will get automatically transformed to camelCase, and I know how to turn this off globally but how do I turn this off for one single action ? I know it was supposed to be something like

return Json(myObj, cfgHere); 

but can't find this example anywhere

1

There are 1 best solutions below

0
On BEST ANSWER

The Json method is part of Controller, but isn't part of ControllerBase. If you're using ControllerBase, which is typical for controllers that don't use views, you can new up a JsonResult and return that:

return new JsonResult(myObj, cfgHere);

This is all the Controller.Json method really does, as can be seen in the source:

public virtual JsonResult Json(object data, object serializerSettings)
{
    return new JsonResult(data, serializerSettings);
}

serializerSettings can be either JsonSerializerOptions or JsonSerializerSettings (if you're using Json.NET). Here's an example that assumes you're using the default, System.Text.Json-based formatters:

return new JsonResult(myObj, new JsonSerializerOptions());

By creating an instance of JsonSerializerOptions without setting any properties, the PropertyNamingPolicy is left as the default policy, which leaves the property names as-is.

If you'd like to use a more declarative approach, which supports content-negotiation, see: Change the JSON serialization settings of a single ASP.NET Core controller.