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?
Asked
Active
Viewed 631 times
3
-
1what version of .net are you using? – Andy-Delosdos Aug 17 '16 at 13:19
-
is this of any use: http://stackoverflow.com/questions/19956838/force-camelcase-on-asp-net-webapi-per-controller you might be able to set the resolver per controller. – Andy-Delosdos Aug 17 '16 at 13:21
-
1@Delosdos this is for a .NET 4.6 library, not for a specific web framework. – ChaseMedallion Aug 17 '16 at 13:29
1 Answers
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