snake_case JSON with ASP.NET Core MVC

ASP.NET Core MVC uses camel-cased JSON by default. The property with a name “FirstName” gets serialized into “firstName”. Same, on the way in. There is another style: Snake case. Twitter, for example, uses snake-cased JSON. See this. It is possible to get ASP.NET Core MVC deal with snake-cased JSON. You will just need to change the ConfigureServices method of Startup as follows.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(jo =>
    {
        jo.SerializerSettings.ContractResolver = new DefaultContractResolver()
        {
            NamingStrategy = new SnakeCaseNamingStrategy()
        };
    });
}

Now, consider the following controller and DTO classes.

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new Employee() { FirstName = "Yellow", LastName = "Lemon"});
    }

    [HttpPost]
    public IActionResult Post([FromBody]Employee e)
    {
        return Ok();
    }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

HTTP GET on /api/values will produce a JSON like this.

{"first_name":"Yellow","last_name":"Lemon"}

You can also post the same JSON and the parameter in the method Post will be bound correctly to the JSON payload.

POST http://localhost:5000/api/values HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Content-Length: 43

{"first_name":"Yellow","last_name":"Lemon"}
Advertisements

One thought on “snake_case JSON with ASP.NET Core MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s