Reputation: 420
Following the approach in Easy JSON (un)marshalling in Scala with Jackson, I have defined a JsonUtil
class:
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)
}
And now I want to serialize a class containing an Int
and another Int
with double the value:
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
I realize that Jackson might not recognize a field defined by def
. However, defining doubleX
by def
instead of val
ensures that its value is always correct. Any workaround to make def
and Jackson compatible?
Upvotes: 0
Views: 107
Reputation: 170755
def
doesn't define a field, it's a method. Just annotate the def
with @JsonProperty
and Jackson should consider it as a getter for a "logical property".
Upvotes: 2