Let’s say that we have a JsonNode
object jsonNodeObj
that needs to be parsed to one of multiple classes ClassA
, ClassB
, ClassC
, etc. I could do the following (couldn’t be more ugly):
val mapper = ObjectMapper()
return try {
mapper.treeToValue(jsonNodeObj, ClassA::class.java)
} catch (e1: Exception) {
try {
mapper.treeToValue(jsonNodeObj, ClassB::class.java)
} catch (e2: Exception) {
try {
mapper.treeToValue(jsonNodeObj, ClassC::class.java)
} catch (e3: Exception) {
...
}
}
}
Is there a better way like using when
somehow?
PS:
msrd0 gave a good lead on this. However, I’m still stuck on finding a clean and concise way to solve this.