49

On RC2 the same code returns json format with camel case. After netcore 1.0 release i started new project and the same code is returning json in lowercase.

Tried multiple solutions but none of them were working web-api-serialize-properties-starting-from-lowercase-letter

Brivvirs
  • 2,461
  • 3
  • 18
  • 31

3 Answers3

110
services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });

This keeps a JSON object's name the same as .NET class property.

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Brivvirs
  • 2,461
  • 3
  • 18
  • 31
36

You can configure JSON behavior this way:

public void ConfigureServices(IServiceCollection services)  
  {
      services.AddMvc()
                  .AddJsonOptions(options =>
                  {
                      options.SerializerSettings.ContractResolver =
                          new CamelCasePropertyNamesContractResolver();
                  });
  }
Siavash Rostami
  • 1,883
  • 4
  • 17
  • 31
  • 7
    this actually now is the default behavior (unfortunately), he wanted Default, as is, no change in property names, case – Omu Jul 21 '16 at 18:51
  • 2
    @Omu These actually aren't the same (in .net core 2.0 anyway). The *DefaultContractResolver* will accept CamelCase and return TitleCase, the *CamelCasePropertyNamesContractResolver* accepts and returns CamelCase. – JMK Dec 10 '17 at 14:33
  • @Omu has this changed from .net core 1.x to 2.0 ? – Hinrich Jan 31 '18 at 10:49
0

You can also do this at the individual serializer level, instead of at the global level.

For example, to return an object as JSON on a controller action method you can do this:

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() };

return new JsonResult(myObject, jsonSerializerSettings);

And the resulting JSON string will be in the expected PascalCase to match the .NET class/properties names

Jesus Campon
  • 422
  • 4
  • 4