Home > Software design >  How to get API response key values in PascalCase as same as the object variable name in .net core 3.
How to get API response key values in PascalCase as same as the object variable name in .net core 3.

Time:09-29

This is my Object Class

public class MyObject
{
   Public string Var1 { get; set; }
   Public string Var2 { get; set; }
}

This is a get function of my controller class

[HttpGet]
    public IActionResult GetObjList()
    {
      return Ok(new GenericModel<List<MyObject>>
      {
            Data = myobjectList
      });
 }

The GenericModel contains

public class GenericModel<T>
{
    public T Data { get; set; }
    public string[] Errors { get; set; }
}

My expected result look like this

{
"Data": [
    {
        "Var1": "val1",
        "Var2": "val2"
    }
        ]
}

But I'm getting this,

{
"data": [
    {
        "var1": "val1",
        "var2": "val2"
    }
        ]
}

I just want to get the output key values as same as the object variables, (in PascalCase) I tried the solutions to add "AddJsonOptions" into the Startup.cs but they did not work. And I want the response as Pascal case, only for this controller requests, not in all requests including other controllers. (Sounds odd, but I want to try it) Are there any solutions? Is is impossible?

CodePudding user response:

There may be another solution but I suggest building ContentResult yourself with JsonSerializer:

[HttpGet]
public IActionResult GetObjList()
{
    return this.Content(JsonSerializer.Serialize(yourResult, yourJsonOption), "application/json");
}

CodePudding user response:

For Pascal Case serialization use this code in Startup.cs:

services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy= null;
        );
  • Related