0

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?

SupunV
  • 1
  • 2

2 Answers2

0

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");
}
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
0

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

services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy= null;
        );
Kazi Rahiv
  • 529
  • 3
  • 6
  • Thank you. This is working. Is there any way to implement this method only for selected controller classes? If I do the above method in Startup.cs, my existing code will break. I just wanted to change my code base step by step without affecting all the code at once. – SupunV Sep 29 '22 at 07:21
  • Glad to know that, Please accept the answer then. About using in specific controller action, you can use options while serializing like this var person = JsonSerializer.Parse(json, options); – Kazi Rahiv Sep 29 '22 at 07:24