按照Easy JSON (un)marshalling in Scala with Jackson中的方法,我定义了一个JsonUtil
类:
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object JsonUtil {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.enable(DeserializationFeature.USE_LONG_FOR_INTS)
def toJsonNode[T](elem: T): JsonNode = mapper.valueToTree(elem)
}
现在我要序列化一个包含Int
和另一个Int
的类,该类的值加倍:
import JsonUtil.toJsonNode
trait X {
def x: Int
def doubleX: Int = x * 2
}
case class Three() extends X {
val x = 3
}
println(toJsonNode(Three()))
// {"x":3}
println(Three().doubleX)
// 6
我意识到Jackson可能无法识别def
定义的字段。但是,用doubleX
而不是def
定义val
可以确保其值始终正确。是否有使def
和Jackson兼容的解决方法?