0

I have 2 JSON formats(example_json1, example_json2) and a simple class Address for JSON parsing using Scala. I can get JSON with field type String or StringWrapper.

How can I generalized them?

Now, this code can convert the only "example_json1" to Address object.

object AdressJson {
  val example_json1 =
    """{
      "value":
         {
           "string":"MY ADDRESS"
         }
    }"""

  val example_json2 =
    """{
      "value":"STREET"
    }"""
}



object Main {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def main(args: Array[String]): Unit = {
    val parsedJson = mapper.readValue(AdressJson.example_json1, classOf[Address])
    println(parsedJson)
  }
} 



case class Address(value: StringWrapper)

case class StringWrapper(string: String)

I want to have such code that could work with both these types (and maybe even more types).

Can I create universal code for this without using instanceOf as in Java? What are the approaches in Scala to solve this problem? Can I create a deserializer for it?

javadranik
  • 115
  • 4
  • If you used `json4s` you could create a custom serializer for `StringWrapper` which would accept both formats. See my answer to [this question](https://stackoverflow.com/questions/54322448/how-to-deserialize-a-scala-tree-with-json4s) for an example of a custom serializer. – Tim Jan 29 '19 at 10:11
  • Thanks, but I have to use only Jackson – javadranik Jan 29 '19 at 10:19

1 Answers1

0

My solution:

case class Address(@JsonDeserialize(using = classOf[AdminStatusDesializer])
                   value: StringWrapper)

class AdminStatusDesializer extends JsonDeserializer[StringWrapper]{
 override def deserialize(p: JsonParser, ctxt: DeserializationContext): StringWrapper = {
   val oc = p.getCodec()
   val node:JsonNode  = oc.readTree(p)
   if(node.isNull)StringWrapper(null)
   if(node.isTextual) StringWrapper(node.asText())
   else StringWrapper(node.get("string").asText())
 }
}
javadranik
  • 115
  • 4