当我做一个GET请求来检索我的person列表时,枚举(Title)被转换成整数:
class Person {
public Title PersonTitle{ get; set;}
public string Name { get; set;}
}
enum Title {
STUDENT,
TEACHER,
DIRECTOR
}
假设我们有以下情况:
Person first = new Person(){
PersonTitle = Title.STUDENT,
Name = "Dave"
}
这将导致以下JSON:
[
{
"Name" : "Dave",
"PersonTitle" : 1,
}
]
如何获得枚举的实际值(在本例中为STUDENT) ?
唯一需要修改的代码是:
前:
public enum Title {
STUDENT,
TEACHER,
DIRECTOR
}
>:using using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Title {
STUDENT,
TEACHER,
DIRECTOR
}
现在响应看起来像:
[
{
"Name" : "Dave",
"PersonTitle" : "Student",
}
]
您需要为JSON序列化器添加适当的转换器。
System.Text.Json
:
- 使用JsonStringEnumConverter类
Json.NET
:
- 使用StringEnumConverter类
可以设置JsonConverterAttribute
class Person {
[JsonConverter(typeof(StringEnumConverter))]
public Title PersonTitle{ get; set;}
public string Name { get; set;}
}
用EnumMemberAttribute更新枚举
enum Title {
[EnumMember(Value = "Student")]
STUDENT,
[EnumMember(Value = "Teacher")]
TEACHER,
[EnumMember(Value = "Director")]
DIRECTOR
}