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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What namespace/references does this require. There is no 'AddJsonOptions' that I'm able to see
Its MVC6.namespace Microsoft.Extensions.DependencyInjection // Extensions methods for configuring MVC via an Microsoft.Extensions.DependencyInjection.IMvcBuilder. class MvcJsonMvcBuilderExtensions
thanks !! i have the same Problem this one work fine
36

You can configure JSON behavior this way:

public void ConfigureServices(IServiceCollection services)  
  {
      services.AddMvc()
                  .AddJsonOptions(options =>
                  {
                      options.SerializerSettings.ContractResolver =
                          new CamelCasePropertyNamesContractResolver();
                  });
  }

3 Comments

this actually now is the default behavior (unfortunately), he wanted Default, as is, no change in property names, case
@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.
@Omu has this changed from .net core 1.x to 2.0 ?
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

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.