I'm using Asp.net Core Razor Pages and I'm returning json. I need the json to be in camel casing across the board, therefore I tried to set the resolver in Startup.cs like this
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
However this does not work, the razor page is still returning json in Pascal casing. How do I correct the issue? Thank you.
When you use AddJsonOptions
, you are configuring an instance of JsonSerializerSettings
that is specific to ASP.NET Core MVC. When you use JsonConvert.SerializeObject
, you're using a different instance of JsonSerializerSettings
. In order to affect that instance, you can use JsonConvert.DefaultSettings
, like so:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Unfortunately, changes you make to DefaultSettings
do not apply to the instance that's configured via AddJsonOptions
- You'll need to configure those separately. You can see how that is a separate instance that gets created by a JsonSerializerSettingsProvider
in the source, if you're interested.