Home > Net >  Use JsonProperty if it exists otherwise use camelcase
Use JsonProperty if it exists otherwise use camelcase

Time:06-28

I have the following class:

public sealed class CRMUser
{
    /// The display name.
    /// </value>
    [JsonProperty("name")]
    public string DisplayName { get; set; }

    [JsonProperty("email")]
    public string EmailAddress { get; set; }

    [JsonProperty("phone")]
    public string PhoneNumber { get; set; }
}

Which when I returned it as Json in a controller eg

return Json(crmUser);

it was returning the object with camel case and ignoring the JsonProperty attributes. To get around this, I had to add the following:

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        // this allows us to use the JsonProperty attribute when returning Json in an action
        options.SerializerSettings.ContractResolver = new DefaultContractResolver(); // this resolver is from newtonsoft.json
    });

This works but now any class that I haven't used JsonProperty attribute on is no longer camel case - is there a way to get it to use the property if it exists and if not, fall back to camel casing?

CodePudding user response:

To tell Json.Net to use camel casing by default, you have to provide that option when creating the DefaultContractResolver:

DefaultContractResolver contractResolver = new DefaultContractResolver
{
    NamingStrategy = new CamelCaseNamingStrategy()
};

The docs go into more details.

  • Related