4

I have two controller FooController and BooController (the last is for a backward compatibility), I want only the FooController will return its model with upper camel case notation ("UpperCamelCase").

For example:

public class MyData 
{
    public string Key {get;set;}
    public string Value {get;set;} 
}

public class BooController : ControllerBase 
{
    public ActionResult<MyData> GetData() { ... } 
} 
public class FooController : ControllerBase 
{
    public ActionResult<MyData> GetData() { ... } 
}

The desired GET output:

GET {{domain}}/api/Boo/getData 
[
    {
        "key": 1,
        "value": "val"
    } 
]

GET {{domain}}/api/Foo/getData 
[
    {
        "Key": 1,
        "Value": "val"
    } 
]

If I'm using the AddJsonOptions extension with option.JsonSerializerOptions.PropertyNamingPolicy = null like:

services.AddMvc()
.AddJsonOptions(option =>
{
    option.JsonSerializerOptions.PropertyNamingPolicy = null;
});

both BooController and FooController returns the data with upper camel case notation.

How to make only the FooController to return the data in upper camel case notation format?

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91

2 Answers2

0

Solved (although kind of bad performance and a hacky solution - hoping for someone to suggest a better solution):

Inside the legacy BooController I'm serializing the response just before returning it using a custom formater of JsonSerializerSettings:

public class BooController : ControllerBase 
{
    public ActionResult<MyData> GetData() 
    {
        var formatter = JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        return Ok(JsonConvert.SerializeObject(response, Formatting.Indented, formatter()));
    } 
}

Result in:

GET {{domain}}/api/Boo/getData 
[
    {
        "key": 1,
        "value": "val"
    } 
]
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • You can just return `JsonResult`. return `new JsonResult(response, jsonSerializerSettings)`. Or even you can create method which will take object and ContractResolvers and will create json result. – Farhad Jabiyev Nov 24 '19 at 13:01
0

Add [JsonProperty("name")] in the response class property.

stackoverflow.com/a/34071205/5952008