Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Json.NET serialization settings on a class level

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.

like image 403
Serhii Shushliapin Avatar asked Jun 28 '17 14:06

Serhii Shushliapin


People also ask

Which one is correct class for JSON serializer?

The JsonSerializer is a static class in the System. Text. Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.

What is serialization in JSON?

Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.

How does the JsonProperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is a JSON serialization exception?

The exception thrown when an error occurs during JSON serialization or deserialization.


1 Answers

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;
}
like image 188
TylerBrinkley Avatar answered Sep 28 '22 13:09

TylerBrinkley