Skip to content

Instantly share code, notes, and snippets.

@daharon
Created April 8, 2022 21:55
Show Gist options
  • Save daharon/7db656741ea30754505155646dee839a to your computer and use it in GitHub Desktop.
Save daharon/7db656741ea30754505155646dee839a to your computer and use it in GitHub Desktop.
Custom Jackson deserializer registered with the mapper
package us.aharon.test.json
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonNode}
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object JacksonRegisteredSerializers extends App {
/**
* Custom Jackson deserializer for BigInt.
*
* Expects [[BigInt]] in JSON as a [[String]].
* {{{
* {
* "a_big_int": "123456789123456789"
* }
* }}}
*/
private class BigIntDeserializer extends JsonDeserializer[BigInt] {
override def deserialize(p: JsonParser, ctxt: DeserializationContext): BigInt = {
val node: JsonNode = p.getCodec.readTree(p)
BigInt(node.asText)
}
}
// Define a module for the custom deserializer.
val bigIntModule = new SimpleModule()
.addDeserializer(classOf[BigInt], new BigIntDeserializer())
val mapper = JsonMapper.builder()
.addModule(DefaultScalaModule) // Register the module with the mapper.
.addModule(bigIntModule)
.build()
/**
* Our example object as a target for deserialization.
*/
case class ExampleObj(
@JsonProperty("a_big_int")
val aBigInt: BigInt
)
val example =
"""
|{
| "a_big_int": "123456789123456789"
|}
|""".stripMargin
// Deserialize
val actual = mapper.readValue(example, classOf[ExampleObj])
val expected = ExampleObj(BigInt("123456789123456789"))
println(s"Deserialized ExampleObj: $actual")
assert(actual == expected)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment