Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set up snake case JSON for dotnet core api?

I've managed to serialize the api responses to the snake_case naming convention by using the following in my Startup.cs. This way it returns my DTO's as snake cased JSON.

services
     .AddMvc()
     .AddJsonOptions(x =>
     {
         x.SerializerSettings.ContractResolver = new DefaultContractResolver
         {
             NamingStrategy = new SnakeCaseNamingStrategy()
         };
     });

That is the half of what I want. But when I post snake-cased JSON, see below for an example, it will not bind the values to my DTO on the api. For example the UserProfile array and the CreatedOn, ModifiedOn are not getting any values.

{
   "user_profiles": [
      {
         "id": 1,
         "created_on": "2017-02-08T19:54:59.370Z",
         "modified_on": "2017-02-18T14:10:42.248Z",
         "email": "[email protected]",
         "username": "my_username"
      }
   ],
   "id": 1,
   "created_on": "2017-02-08T19:50:31.690Z",
   "modified_on": 2017-02-08T19:50:31.690Z,
   "name": "My Company Name"
} 

What is the proper way to set it up so that the API handles snake cased JSON when send to the api and send it as snake case when requested from the api?

My DTO's

 public class CompanyDto
 {
      public int Id { get; set; }
      public DateTime CreatedOn { get; set; }
      public DateTime ModifiedOn { get; set; }
      public string Name { get; set; }
      public IEnumerable<UserProfileDto> UserProfiles { get; set; }
 }

 public class UserProfileDto
 {
      public int Id { get; set; }
      public DateTime CreatedOn { get; set; }
      public DateTime ModifiedOn { get; set; }
      public string Email { get; set; }
      public string Username { get; set; }
 }

My PUT action on the controller

[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, [FromBody]CompanyDto value)
{
     // Body
}

EDIT:

Alright turns out that I was missing some values in the JSON I posted to the API. They were required by the api but did not get any error or somethings.

So to answer the question, in my experience using the following is enough for snake casing the JSON output / input for a dotnet core api. Instead it just made the expected model null sigh.

services
     .AddMvc()
     .AddJsonOptions(x =>
     {
         x.SerializerSettings.ContractResolver = new DefaultContractResolver
         {
             NamingStrategy = new SnakeCaseNamingStrategy()
         };
     });
like image 264
Tom Aalbers Avatar asked Feb 20 '17 20:02

Tom Aalbers


1 Answers

Since ASP.NET Core 3.0

services.AddMvc().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy()
    };
});
like image 74
Hung Quach Avatar answered Oct 01 '22 18:10

Hung Quach