ChaseMedallion
ChaseMedallion

Reputation: 21764

How can I opt out of a JSON contract resolver

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?

Upvotes: 3

Views: 685

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129787

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:

Upvotes: 3

Related Questions