Skip to content

Jackson JSON

grant-guo edited this page Apr 23, 2021 · 1 revision
case class Root(
  stems: List[Stem]  
)

case class Stem(
  name: String,
  leafs: List[Leaf]
)

case class Leaf(
  name: String,
  @JsonDeserializer(using = classOf[PropDeserializer])
  @JsonSerializer(using = classOf[PropSerializer])
  prop1: Int
)

class PropDeserializer extends StdDeserializer[Int](classOf[Int]) {
    override def deserialize(jsonParser: JsonParser, deserializationContext: DeserializationContext): Int = jsonParser.getText.trim.toInt
}

class PropSerializer extends StdSerializer[Int](classOf[Int]) {
    override def serialize(t: Int, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
      jsonGenerator.writeInt(t)
    }
  }

lazy val jsonMapper = JsonMapper.builder().addModule(DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build()

val root: Root = jsonMapper.readValue(..., classOf[Root])