我有一个包含枚举属性的类,在使用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)也是受欢迎的。
注意,当存在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; }
@Iggy回答设置JSON序列化c# enum字符串仅为ASP。NET (Web API等等)。
但是为了使它也适用于特殊的序列化,在开始类中添加以下内容(如Global。asax Application_Start)
//convert Enums to Strings (instead of Integer) globally
JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
return settings;
});
更多关于Json的信息。网络页面
此外,要让枚举成员序列化/反序列化特定文本,请使用
System.Runtime.Serialization.EnumMember
属性,像这样:
public enum time_zone_enum
{
[EnumMember(Value = "Europe/London")]
EuropeLondon,
[EnumMember(Value = "US/Alaska")]
USAlaska
}
在。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 }
对于。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