I have the following Scala case class:
case class InteractionPersona(
id: String,
geo: Option[(Option[String], Option[String], Option[String])])
Using Jackson when I serialize an instance of a class:
val persona = InteractionPersona("123", Some((Some("canada"), None, None)))
val json = mapper.writeValueAsString(persona)
I get the following JSON:
{"id": "123", "geo": ["canada", null, null]}
which is a perfectly acceptable representation for my needs. However, during deserialization, I get com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of VALUE_NULL token:
val actual = mapper.readValue(json, classOf[InteractionPersona])
It nulldoesn't seem to be a valid value String, but since I am deserializing Scala Option[String], it nullshould be represented as a value None.
In How to deserialize Jackson Json NULL String to Date using JsonFormat , @wassgren suggested using a converter using annotation JsonDeserialize, and after reading the documentation, I chose to use the options contentUsing:
case class InteractionPersona(
id: String,
@JsonDeserialize(contentUsing = classOf[GeoConverter])
geo: Option[(Option[String], Option[String], Option[String])])
class GeoConverter extends JsonDeserializer[Option[(Option[String], Option[String], Option[String])]] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): Option[(Option[String], Option[String], Option[String])] = {
throw new RuntimeException("tada")
}
}
, . contentConverter :
@JsonDeserialize(contentConverter = classOf[GeoConverter])
class GeoConverter extends StdConverter[String, Option[String]] {
override def convert(value: String): Option[String] = {
throw new RuntimeException("tada")
}
}
String ?