Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON returns properties in PascalCase instead of camelCase

Using Microsoft.AspNetCOre.OData 7.0.1, if I have a list of Models that are NOT in the database, the JSON result always comes back as PascalCase instead of camelCase. How can I get my list to be camelCase?

Relative example below:

My model that is NOT in the database.

public class Widget 
{
   public string Id { get; set; }
   public string Name { get; set; }
}

My controller

[Route("api/[controller]")]
public class WidgetController : ODataController 
{
    [EnableQuery()]
    public IActionResult GetWidgets() 
    {
        // Create list of ten Widgets
        var widgetsList = new List<Widget>();

        for(var i = 0; i < 10; i++) {
            widgetsList.Add(new Widget() { Id = i, Name = $"Widget {i}" });
        }

        return this.Ok(widgetsList);
    }       
}

/api/GetWidgets?$select=name returns in the following format

{ Name: "Widget" } 
like image 711
Johnny Avatar asked Aug 24 '18 19:08

Johnny


1 Answers

Option 1

Even though Widget is not in the database, you can add it to the Entity Data Model (EDM). The EDM probably has camel case as its convention. Widget will pick up that convention.

var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();

builder.EntitySet<Widget>("Widgets");

_edmModel = builder.GetEdmModel();

Here is a sample OData fork of the odata/webapi repository.

Option 2

Set the MVC JSON options in ConfigureServices. Now JSON responses will be in camel case.

services
    .AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = 
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    });
like image 134
Shaun Luttin Avatar answered Nov 14 '22 22:11

Shaun Luttin