3

We have a Json.NET setup which sets the contract resolver to be the CamelCasePropertyNamesContractResolver. However, for some types I would like to opt out of the camelCasing behavior. Is it possible to do this by annotating those types in some way?

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152

1 Answers1

3

Yes, as of Json.Net version 9.0.1 (June 2016), both the [JsonObject] and [JsonProperty] attributes support a NamingStrategyType parameter. So you can use a CamelCasePropertyNamesContractResolver to set up the default naming scheme, but then opt out or even change to a different strategy using these attributes for specific classes or properties.

Here is a short demo:

public class Program
{
    public static void Main(string[] args)
    {
        Foo foo = new Foo
        {
            CamelCasedProperty = "abc def",
            AlsoCamelCasedButChildPropsAreNot = new Bar
            {
                SomeProperty = "fizz buzz",
                AnotherProperty = "whiz bang"
            },
            ThisOneOptsOutOfCamelCasing = "blah blah",
            ThisOneIsSnakeCased = "senssssational"
        };

        var settings = new JsonSerializerSettings
        {
            // set up default naming scheme
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Formatting = Formatting.Indented
        };

        string json = JsonConvert.SerializeObject(foo, settings);
        Console.WriteLine(json);
    }
}

class Foo
{
    public string CamelCasedProperty { get; set; }
    public Bar AlsoCamelCasedButChildPropsAreNot { get; set; }

    [JsonProperty(NamingStrategyType = typeof(DefaultNamingStrategy))]
    public string ThisOneOptsOutOfCamelCasing { get; set; }

    [JsonProperty(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public string ThisOneIsSnakeCased { get; set; }
}

[JsonObject(NamingStrategyType = typeof(DefaultNamingStrategy))]
class Bar
{
    public string SomeProperty { get; set; }
    public string AnotherProperty { get; set; }
}

Output:

{
  "camelCasedProperty": "abc def",
  "alsoCamelCasedButChildPropsAreNot": {
    "SomeProperty": "fizz buzz",
    "AnotherProperty": "whiz bang"
  },
  "ThisOneOptsOutOfCamelCasing": "blah blah",
  "this_one_is_snake_cased": "senssssational"
}

Fiddle:

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • What if I don't have access to class Bar (because it's from 3rd party) but I actually want to force AlsoCamelCasedButChildPropsAreNot to have all its to have its properties CamelCase? Is there a way to do that just through attributes decorator? See [question](https://stackoverflow.com/questions/46326475/how-can-i-make-the-properties-of-sub-class-camel-case) – CodeHacker Sep 21 '17 at 06:24