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

I want to deserialize enums into their string representation and vice versa using json.net. The only way I can define a structure to apply its StringEnumConverter is to annotate the given properties as follows:

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

However, in my case it would be much more convenient to configure json.net all over the world so that all enumerations get (de) serialized using StringEnumConverter without the need for additional annotations.

Is there any way to do this, for example. using custom JsonSerializerSettings ?

+73
json c #
Sep 15 '11 at 8:25
source share
3 answers

Add a StringEnumConverter to the JsonSerializerSettings converter JsonSerializerSettings .

Documentation: Serialization with JsonConverters




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

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

This will serialize SomeValue to SomeValue .

+104
Sep 15 '11 at 10:29
source share

Other answers work for ASP.NET, but if you want to set these parameters, usually to call 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 )

+34
01 Oct '13 at 16:44
source share

In your application Global.asax.cs

 HttpConfiguration config = GlobalConfiguration.Configuration; config.Formatters.JsonFormatter.SerializerSettings.Converters.Add (new Newtonsoft.Json.Converters.StringEnumConverter()); 
+18
Aug 09 '13 at 17:59
source share



All Articles