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?