You probably want a combination here (I’m not that familiar with ObjectMapper
, but canDeserialize
could avoid the try/catch. The rest is as follows:
fun <T> ObjectMapper.treeToValueOrNull(n: TreeNode, valueType: Class<T>):T? = try {
treeToValue(n, valueType)
} catch (e: JsonProcessingException) {
null
}
val mapper = ObjectMapper()
return mapper.treeToValueOrNull(jsonNodeObj, ClassA::class.java) ?:
mapper.treeToValueOrNull(jsonNodeObj, ClassB::class.java) ?:
mapper.treeToValueOrNull(jsonNodeObj, ClassC::class.java) ?:
throw IllegalArgumentException("The node doesn't map to A, B or C")
Btw. you may make it prettier by using a refied type parameter on an inline version