10

I want my class to be serialized and deserialized using camel case naming convention. I know I can use the JsonConvert.SerializeObject(object, settings) overload as stated here:

var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(product, serializerSettings);

Is there any way to apply the same configuration on a class level (via attributes) so that I do not need to override the serialization settings?

I could write a custom converter but that looks like an overkill for such a simple thing.

Serhii Shushliapin
  • 2,528
  • 2
  • 15
  • 32

1 Answers1

24

If you're using Json.NET 9.0.1 or later you can use the NamingStrategyType property on the JsonObjectAttribute to achieve what you want. If you need to pass arguments to the NamingStrategy's constructor then specify them with the NamingStrategyParameters property. Below is an example of how to specify a class with a camel case naming strategy.

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Foo
{
    public string Bar;
}
TylerBrinkley
  • 1,066
  • 10
  • 16
  • That is exactly what I need! I saw this approach in [docs](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_CamelCaseNamingStrategy.htm) but I haven't found the necessary classes in my solution (as I figured out later, simply because it's based on v6.0.8). Since I'm working on a part of a bigger platform, I need to know if updating the Newtonsoft version may cause unexpected issues. Any input on that? Is it possible to achieve the goal using Newtonsoft 6? – Serhii Shushliapin Jun 28 '17 at 15:13
  • I know the library's author doesn't make many breaking changes so you probably won't have issues with that but I'm not sure what other issues you may have by updating Json.NET. Perhaps just try and see. As for doing this with Json.NET 6 I'm really not sure how you can accomplish that. You might be able to do it with a custom ContractResolver or a custom JsonConverter but I'm not sure. – TylerBrinkley Jun 28 '17 at 15:27
  • It does not apply the camel case convention to properties of a base class... So if I apply the attribute on a subclass, I've got half of my props in cammel case and all the rest serialized using the default settings.. (v10.0.3) – Serhii Shushliapin Jun 28 '17 at 15:52
  • I suggest you create a feature request to [GitHub](https://github.com/JamesNK/Newtonsoft.Json/issues) to add a property to NamingStrategy to process base class members. – TylerBrinkley Jun 28 '17 at 16:25
  • For now, if you have access to modify the base class and want it to always serialize as camel case then you could add `JsonObjectAttribute` with `NamingStrategyType` to the base class. – TylerBrinkley Jun 28 '17 at 16:42