我正在Kotlin中编写一个Spring Boot项目。我拥有的POJO /数据类之一
data class Employee(
//... other properties
val designation: Designation
)
enum class Designation {
JUN, MID, SEN
}
默认情况下,此
Employee
对象序列化为{"designation" : "JUN"}
。我想添加一个自定义序列化程序,以便该对象将像{"designation" : "Junior"}
这样进行序列化。我添加的序列化器,
@JsonComponent
class DesignationSerialization {
class Serializer: JsonObjectSerializer<Designation>() {
override fun serializeObject(designation: Designation, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString(designation.pretty)
}
private val Designation.pretty: String
get() = when(this) {
Designation.JUN -> "Junior"
Designation.MID -> "Mid-Level"
Designation.SEN -> "Senior"
}
}
}
但是在运行此程序时,出现此错误,
JSON encoding error: Can not write a string, expecting field name (context: Object); nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not write a string, expecting field name (context: Object)
我也尝试过使用
gen.writeStringField("designation", designation.pretty)
,但是这样可以序列化对象{
"designation": {"designation": "Mid-Level"}
}
最佳答案
您应该在枚举类中添加一个属性,并用@JsonValue
标记https://www.baeldung.com/jackson-serialize-enums
关于java - 使用自定义 jackson 序列化器替换Enum值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62143197/