我有一个包含枚举属性的类,在使用JavaScriptSerializer序列化对象时,我的json结果包含枚举的整数值,而不是它的字符串“name”。有没有一种方法来获得枚举作为字符串在我的json而不必创建一个自定义JavaScriptConverter?也许有一个属性,我可以装饰枚举定义,或对象属性?

举个例子:

enum Gender { Male, Female }

class Person
{
    int Age { get; set; }
    Gender Gender { get; set; }
}

期望的JSON结果:

{ "Age": 35, "Gender": "Male" }

理想情况下,用内置的。net框架类来寻找答案,如果没有可能的替代方案(如Json.net)也是受欢迎的。


当前回答

将以下内容添加到全局中。asax用于JSON序列化c# enum为字符串

  HttpConfiguration config = GlobalConfiguration.Configuration;
            config.Formatters.JsonFormatter.SerializerSettings.Formatting =
                Newtonsoft.Json.Formatting.Indented;

            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
                (new Newtonsoft.Json.Converters.StringEnumConverter());

其他回答

对于任何在22年5月就需要。net 6解决方案并且仍在使用Newtonsoft的人来说,你可以像这样全局注册转换器:

var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddControllers(options => options.RespectBrowserAcceptHeader = true)
.AddNewtonsoftJson(opt =>
{
    opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
    opt.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
})
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();

对于。net 6.0,如果你想使用内置的JsonSerializer (System.Text.Json)

然后,它是开箱即用的,你只需要使用内置的JsonStringEnumConverter属性。例如:

[JsonConverter(typeof(JsonStringEnumConverter))]
public SomeEnumType EnumProperty { get; set; }

就是这样,但是要确保你的SomeEnumType包含了精确的字符串值,否则它会抛出异常。套管似乎不敏感。

参考:https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties?pivots=dotnet-6-0 # enums-as-strings

在。net core 3中,现在可以使用System.Text.Json中的内置类来实现这一点(编辑:System.Text.Json也可以作为。net core 2.0和。net framework 4.7.2以及更高版本的NuGet包,根据文档):

var person = new Person();
// Create and add a converter which will use the string representation instead of the numeric value.
var stringEnumConverter = new System.Text.Json.Serialization.JsonStringEnumConverter();
JsonSerializerOptions opts = new JsonSerializerOptions();
opts.Converters.Add(stringEnumConverter);
// Generate json string.
var json = JsonSerializer.Serialize<Person>(person, opts);

为特定的属性配置JsonStringEnumConverter属性装饰:

using System.Text.Json.Serialization;

[JsonConverter(typeof(JsonStringEnumConverter))]
public Gender Gender { get; set; }

如果您希望始终将枚举转换为字符串,请将属性放在枚举本身。

[JsonConverter(typeof(JsonStringEnumConverter))] 
enum Gender { Male, Female }

ASP。NET核心方式:

public class Startup
{
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    services.AddMvc().AddJsonOptions(options =>
    {
      options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
    });
  }
}

https://gist.github.com/regisdiogo/27f62ef83a804668eb0d9d0f63989e3e

Asp。Net Core 3与System.Text.Json

public void ConfigureServices(IServiceCollection services)
{

    services
        .AddControllers()
        .AddJsonOptions(options => 
           options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())
        );

    //...
 }