杰克逊用整数值反序列化scala枚举
Jackson Deserialize scala enum with integer value
我正在尝试从整数值反序列化 Scala 枚举。
object TestEnum extends Enumeration {
type TestEnum = Value
val None = Value(0)
val One = Value(1)
val Two = Value(2)
val Four = Value(4) // scalastyle:ignore
@JsonCreator
def forValue(value: Int): TestEnum = {
TestEnum.Value(value)
}
}
class TestEnum extends TypeReference[TestEnum.type]
当我尝试反序列化该字段时,它会抛出错误 - Cannot deserialize value of type
com.example.TestEnum$from Integer value (token
JsonToken.VALUE_NUMBER_INT)
我看到 jackson 文档建议在 java 中使用 JsonCreator,但是没有提到 scala 枚举。
我这里使用的是 defaultScalaMapper,没有任何定制。
我能够使用枚举在 class 中使用 jsonCreator 解决它。如下-
class Example(testEnum: TestEnum) {
@JsonCreator
def this(testEnumNum: Int) = {
this(TestEnum.forValue(testEnumNum))
}
}
但是我需要在每个 class 中执行此操作,我希望是否有更好的解决方案。
我正在尝试从整数值反序列化 Scala 枚举。
object TestEnum extends Enumeration {
type TestEnum = Value
val None = Value(0)
val One = Value(1)
val Two = Value(2)
val Four = Value(4) // scalastyle:ignore
@JsonCreator
def forValue(value: Int): TestEnum = {
TestEnum.Value(value)
}
}
class TestEnum extends TypeReference[TestEnum.type]
当我尝试反序列化该字段时,它会抛出错误 - Cannot deserialize value of type
com.example.TestEnum$from Integer value (token
JsonToken.VALUE_NUMBER_INT)
我看到 jackson 文档建议在 java 中使用 JsonCreator,但是没有提到 scala 枚举。
我这里使用的是 defaultScalaMapper,没有任何定制。
我能够使用枚举在 class 中使用 jsonCreator 解决它。如下-
class Example(testEnum: TestEnum) {
@JsonCreator
def this(testEnumNum: Int) = {
this(TestEnum.forValue(testEnumNum))
}
}
但是我需要在每个 class 中执行此操作,我希望是否有更好的解决方案。