skip to Main Content

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?

2

Answers


  1. 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");
    }
    
    Login or Signup to reply.
  2. For Pascal Case serialization use this code in Startup.cs:

    services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy= null;
            );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search