如何告诉 Json.Net 在全局范围内将 StringEnumConverter 应用于所有枚举

我想将枚举反序列化为它们的字符串表示形式,反之亦然。我能想到的告诉框架应用它的 StringEnumConverter的唯一方法是像下面这样注释有问题的属性:

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

然而,在我的用例中,在全局范围内配置 json.net 会更加方便,这样所有的枚举都可以使用 StringEnumConverter进行(反)序列化,而不需要额外的注释。

有什么方法可以做到这一点,例如在定制 JsonSerializerSettings的帮助下?

45599 次浏览

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.

In your Global.asax.cs add

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
(new Newtonsoft.Json.Converters.StringEnumConverter());

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)

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.

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() }
);