1

I have an object that I want to serialize to JSON and use camelcase. I have a .Net Core 3 Web Api application and in my startup file I have the following service registrations:

services.AddControllersWithViews();
services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

In my controller I have the following:

var js = JObject.FromObject(obj);

Now, the result of this serialization is something like:

{
 StartRow: 1,
 EndRow: 2
}

When I instantiate a JsonSerializer, and pass it as the second argument, then I get the expected camelcase format:

{
 startRow: 1,
 endRow: 2
}

Here is the code:

var serializer = new JsonSerializer()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
var js = JObject.FromObject(obj, serializer);

This would mean I have to have a serializer for each controller.

I'm wondering if I'm missing something or registering something wrongly.

Thank you.

Marin
  • 861
  • 1
  • 11
  • 27
  • 7
    Your service registration configures how Web API serializes JSON objects in HTTP requests and responses. It doesn't affect the static `JObject.FromObject` method. – Michael Liu Dec 29 '19 at 20:55
  • 1
    If you want to set serializer setting globally see [Set default global json serializer settings](https://stackoverflow.com/q/21815759/3744182). – dbc Dec 30 '19 at 00:13

1 Answers1

4

Try this:

public void ConfigureServices(IServiceCollection services)
{
    //do your stuff..
    services.AddControllers().AddNewtonsoftJson();
    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    //do your stuff..
}

Reference:

Serializing a PascalCase Newtonsoft.Json JObject to camelCase

Rena
  • 30,832
  • 6
  • 37
  • 72