我有一个包含枚举属性的类,在使用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)也是受欢迎的。


当前回答

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

其他回答

这是一个老问题,但以防万一,我想我还是要发表一下。在我的项目中,我为任何Json请求使用单独的模型。模型通常具有与域对象相同的名称,并以“Json”为前缀。模型使用AutoMapper进行映射。通过让json模型声明一个在域类上是enum的字符串属性,AutoMapper将解析为它的字符串表示形式。

如果你想知道,我需要为Json序列化类单独的模型,因为内置的序列化器会提出循环引用,否则。

希望这能帮助到一些人。

将以下内容添加到全局中。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());

对于VB.net,我找到了以下作品:

Dim sec = New Newtonsoft.Json.Converters.StringEnumConverter()
sec.NamingStrategy() = New Serialization.CamelCaseNamingStrategy

Dim JSON_s As New JsonSerializer
JSON_s.Converters.Add(sec)

Dim jsonObject As JObject
jsonObject = JObject.FromObject(SomeObject, JSON_s)
Dim text = jsonObject.ToString

IO.File.WriteAllText(filePath, text)

Omer Bokhari和uri的答案的组合总是我的解决方案,因为我想提供的值通常不同于我在我的枚举,特别是我希望能够改变我的枚举,如果我需要。

如果有人感兴趣的话,大概是这样的:

public enum Gender
{
   [EnumMember(Value = "male")] 
   Male,
   [EnumMember(Value = "female")] 
   Female
}

class Person
{
    int Age { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    Gender Gender { get; set; }
}

注意,当存在Description属性时,没有序列化的答案。

下面是支持Description属性的实现。

public class CustomStringEnumConverter : Newtonsoft.Json.Converters.StringEnumConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Type type = value.GetType() as Type;

        if (!type.IsEnum) throw new InvalidOperationException("Only type Enum is supported");
        foreach (var field in type.GetFields())
        {
            if (field.Name == value.ToString())
            {
                var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                writer.WriteValue(attribute != null ? attribute.Description : field.Name);

                return;
            }
        }

        throw new ArgumentException("Enum not found");
    }
}

枚举:

public enum FooEnum
{
    // Will be serialized as "Not Applicable"
    [Description("Not Applicable")]
    NotApplicable,

    // Will be serialized as "Applicable"
    Applicable
}

用法:

[JsonConverter(typeof(CustomStringEnumConverter))]
public FooEnum test { get; set; }