在kotlin中分解json解析的习惯性方式

假设我们有一个JsonNode对象jsonNodeObj ,它需要被分析到多个类ClassAClassBClassC等中的一个。我可以这样做(不能更丑陋):

 val mapper = ObjectMapper() 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) { ... } } } 

有什么更好的方式就像用when方式?

绝对有更好的方法来做到这一点。 你可以定义一个函数,在成功时返回true,在exception时返回false,例如:

 inline fun  ObjectMapper.treeToValueOrNull(node : TreeNode) : T? = try { treeToValue(node, T::class.java) } catch (ex : Exception) { null } 

这是有效的,因为在Kotlin中trycatch -statements可以有一个返回值。 现在,您可以使用when处理json:

 lateinit var object : Any when { mapper.treeToValueOrNull(jsonNodeObj)?.let { object = it } != null -> dosthA(object as ClassA) mapper.treeToValueOrNull(jsonNodeObj)?.let { object = it } != null -> dosthB(object as ClassB) mapper.treeToValueOrNull(jsonNodeObj)?.let { object = it } != null -> dosthC(object as ClassC) } 

pvvrieze发现了一个更短的解决方案 :

 val object = mapper.treeToValueOrNull(jsonNodeObj) ?: mapper.treeToValueOrNull(jsonNodeObj) ?: mapper.treeToValueOrNull(jsonNodeObj)