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" } 
3
  • 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 minimal reproducible example Commented Aug 24, 2018 at 20:49
  • You need explicit Json converter to convert the result to the relevant case Commented Aug 24, 2018 at 21:14
  • You can use json.net by newtonsoft to serialize into camelCase. Great set of answers here - stackoverflow.com/questions/19445730/… Commented Aug 24, 2018 at 21:31

1 Answer 1

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();
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.