Reputation: 38180
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
?
Upvotes: 90
Views: 50379
Reputation: 337
Install the Swashbuckle.AspNetCore.Newtonsoft package.
services.AddControllers().AddNewtonsoftJson(o =>
{
o.SerializerSettings.Converters.Add(new StringEnumConverter
{
//CamelCaseText = true,//absolete
NamingStrategy = new CamelCaseNamingStrategy()
});
});
services.AddSwaggerGenNewtonsoftSupport();
Upvotes: 1
Reputation: 1701
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() }
);
Upvotes: 7
Reputation: 145940
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.
Upvotes: 6
Reputation: 49042
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
.
Upvotes: 118
Reputation: 4154
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;
});
Upvotes: 42
Reputation: 8669
In your Global.asax.cs add
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
(new Newtonsoft.Json.Converters.StringEnumConverter());
Upvotes: 19