88

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?

Leo
  • 37,640
  • 8
  • 75
  • 100

6 Answers6

118

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.

BanksySan
  • 27,362
  • 33
  • 117
  • 216
James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • I tried setting this on my global.asax.cs under `GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings`but didn't work. Any idea why that could be? – amhed Apr 26 '13 at 20:38
  • Is there any way to lower-case the field name? The CamelCaseText flag is hard-coded into the class and I don't see a way to use a different casing strategy. – mikebridge Oct 08 '13 at 22:20
  • @mikebridge Have you found a solution to this? Also looking for a way to set the name for each enum option myself (or use lowercase). – Timm Jan 29 '14 at 15:08
  • 1
    @Timm Yes, I used this post: http://stackoverflow.com/questions/6288660/net-ensuring-json-keys-are-lowercase/6288726#6288726 – mikebridge Jan 30 '14 at 16:00
  • @mikebridge Thanks. I found that [EnumMember (Value = "undefined")] per enum entry works fine with JSON.Net as well (though unsupported by Microsoft's JSON deserializer) – Timm Jan 30 '14 at 16:23
  • @Timm If you want a finer-grain control you can also use a DataContract and then use a DataMember attribute, e.g. [DataMember(Name = "myfieldname")]. – mikebridge Jan 30 '14 at 17:28
  • Answer is now out of date. V12 obsoletes "CamelCaseText". 'StringEnumConverter.CamelCaseText is obsolete. Set StringEnumConverter.NamingStrategy with CamelCaseNamingStrategy instead.' https://www.newtonsoft.com/json/help/html/NamingStrategyCamelCase.htm – Stephen Mar 05 '19 at 21:35
40

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)

Gaz
  • 4,064
  • 3
  • 32
  • 34
  • 3
    What I was looking for! Even shorter: `JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = { new StringEnumConverter { CamelCaseText = true } } };` – Kapé Mar 30 '15 at 20:41
  • 1
    You saved me! Thanks bro! https://gist.github.com/regisdiogo/27f62ef83a804668eb0d9d0f63989e3e – crthompson Mar 19 '20 at 22:21
18

In your Global.asax.cs add

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
                (new Newtonsoft.Json.Converters.StringEnumConverter());
Iggy
  • 8,463
  • 3
  • 31
  • 21
6

For ASP.NET Core 2 do the following:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                });

        ...

Please note this is not services.AddJsonOptions(...), it must be tagged onto MVC because you're creating settings for MVC.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
6

The previous answers are out of date as of Version 12.0.1. The new way is to use NamingStrategy. https://www.newtonsoft.com/json/help/html/NamingStrategyCamelCase.htm

serializerSettings.Converters.Add(
    new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }
);
Stephen
  • 1,603
  • 16
  • 19
0

Install the Swashbuckle.AspNetCore.Newtonsoft package.

services.AddControllers().AddNewtonsoftJson(o =>
        {
            o.SerializerSettings.Converters.Add(new StringEnumConverter
            {
                //CamelCaseText = true,//absolete
                NamingStrategy = new CamelCaseNamingStrategy()
            });
        });
 services.AddSwaggerGenNewtonsoftSupport();
reza.Nikmaram
  • 179
  • 2
  • 4