Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell Json.Net globally to apply the StringEnumConverter to all enums

I want to deserialize enumerations to their string representation and vice versa with json.net. The only way I could figure out to tell the framework to apply its StringEnumConverter is to annotate the properties in question like this:

[JsonConverter(typeof(StringEnumConverter))] public virtual MyEnums MyEnum { get; set; } 

However, in my use case, it would be much more convenient to configure json.net globally such that all enumerations get (de)serialized using the StringEnumConverter, without the need of extra annotations.

Is there any way to do so, e.g. with the help of custom JsonSerializerSettings?

like image 400
Leo Avatar asked Sep 15 '11 08:09

Leo


People also ask

Can JSON serialize enums?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form.

Are enums serializable c#?

In C#, enums are backed by an integer. Most tools will serialize or save your enums using that integer value.

What is StringEnumConverter c#?

Converts an Enum to and from its name string value. Newtonsoft.Json. JsonConverter. Newtonsoft.Json.Converters.


2 Answers

Add a StringEnumConverter to the JsonSerializerSettings Converters collection.

Documentation: Serialize with JsonConverters


If you want the serializer to use camelCasing, you can set this as well:

SerializerSettings.Converters.Add(     new StringEnumConverter { CamelCaseText = true }); 

This will serialize SomeValue to someValue.

like image 129
James Newton-King Avatar answered Sep 30 '22 21:09

James Newton-King


The other answers work for ASP.NET, but if you want to set these settings generally for calling JsonConvert in any context you can do:

JsonConvert.DefaultSettings = (() => {     var settings = new JsonSerializerSettings();     settings.Converters.Add(new StringEnumConverter {CamelCaseText = true});     return settings; }); 

(See http://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension-data)

like image 43
Gaz Avatar answered Sep 30 '22 21:09

Gaz