1

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?

2
  • Did you try passing in CamelCaseNamingStrategy to the contract resolver? Commented Jun 27, 2022 at 13:31
  • 1
    Perfect, that's done the trick - if you add that as an answer I can accept it. Thanks Commented Jun 27, 2022 at 13:34

1 Answer 1

3

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.

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

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.