6

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" } 
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
Johnny
  • 83
  • 1
  • 5
  • 2
    Since both `Id` and `Name` are `private` (so they wouldn't be serialized to JSON at all), the returned data does not match your code. Please post a [mcve] – Camilo Terevinto Aug 24 '18 at 20:49
  • You need explicit Json converter to convert the result to the relevant case – Mrinal Kamboj Aug 24 '18 at 21:14
  • You can use json.net by newtonsoft to serialize into camelCase. Great set of answers here - https://stackoverflow.com/questions/19445730/how-can-i-return-camelcase-json-serialized-by-json-net-from-asp-net-mvc-controll – bsod_ Aug 24 '18 at 21:31

1 Answers1

9

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();
    });
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467