Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core 3.0.100-preview6 - API Json responses are always camelcase, but my classes are not

I have a .net core 3.0 preview 6 MVC application and API. In the API, I am using a third party class library (that I can't change) which defines the class properties as Pascal cased with the JsonProperty, PropertyName snaked cased eg...

public class Company
{
[JsonProperty(PropertyName = "company_name")]
public string CompanyName { get; set; }

more properties ….
}

The problem is that when I supply these via the api they reach the MVC app as Camel case (the default for .net core 3)... and then can't be Deserialized back the to the class model.

Not matter what I try, the API always produces camel cased JSon, eg. the property above will be called companyName.

I tried,

options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = true } };

options.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new DefaultNamingStrategy { OverrideSpecifiedNames = true } };

I've tried NamingStrategy = null on both camel and default ContractResolver. Also tried setting the NamingStrategy to Snake

But nothing changes the outputted Json, it's always camelcased.

I can see the resulting string is camel cased by using ReadAsStringAsync in the MVC app... I when I use JsonConvert.DeserializeObject, the properties are always null, because neither the name or Json PropertyName match the names in the resulting string.

Is this a bug in .net core previews or am missing something else?

Thanks Mustafa, your suggested duplicate is kinda the same issue with kinda the same solutions that I've already tried i.e. changing the setting of the ContractResolver / NamingStrategy to different values.... however, My issue is that none of the suggested solutions appear to have any effect on the API response it always comes back as camelCased.

Interestingly, when I change the NamingStrategy to say Snake, Swagger shows the schema as set (i.e. snake) but the actual output is still camelCased!!!

Also, I have no control over the base classes so I can't change the names / json properties of the classes I'm attempting to transmit.

like image 933
Gary Thornton Avatar asked Dec 03 '25 09:12

Gary Thornton


1 Answers

Microsoft.AspNetCore.Mvc.NewtonsoftJson

Doesn't come up default. Try to install this nuget package manually to your service project. That worked for me.

like image 143
Recep Yesil Avatar answered Dec 04 '25 23:12

Recep Yesil