【发布时间】:2020-05-04 09:20:26
【问题描述】:
我正在使用 Jackson scala 模块,我需要序列化/反序列化案例对象枚举。序列化工作正常,但是当反序列化返回值时,我得到一个com.fasterxml.jackson.databind.exc.InvalidDefinitionException。有没有办法让它工作?我想避免使用“经典”scala 枚举,因为我会失去定义枚举层次结构的能力。
用于测试的代码:
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
sealed trait Operations { @JsonValue def jsonValue: String }
case object Foo extends Operations { override def jsonValue: String = "Foo" }
case object Bar extends Operations { override def jsonValue: String = "Bar" }
sealed trait RichOperations extends Operations
case object Baz extends RichOperations { override def jsonValue: String = "Baz" }
object JsonUtils extends App {
val jsonMapper = new ObjectMapper() with ScalaObjectMapper
jsonMapper.registerModule(DefaultScalaModule)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def toJson(value: Any): String = jsonMapper.writeValueAsString(value)
def fromJson[T: Manifest](json: String): T = jsonMapper.readValue[T](json)
println(toJson(Foo)) // "Foo"
println(toJson(Bar)) // "Bar"
println(toJson(Baz)) // "Baz"
println(fromJson[Operations](toJson(Foo))) // throws InvalidDefinitionException
println(fromJson[Operations](toJson(Bar)))
println(fromJson[RichOperations](toJson(Baz)))
}
【问题讨论】:
-
看看this example,也许会有帮助
-
@Duelist 我看了示例,但案例类序列化结果是 {"type": "
"},而我的序列化只需要 " "
标签: json scala jackson jackson2