假设我们有一个 JsonNode
对象 jsonNodeObj
需要解析为多个类之一 ClassA
, ClassB
、ClassC
等。我可以执行以下操作(不能更丑陋):
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,在异常时返回 false,如下所示:
inline fun <reified T : Any> ObjectMapper.treeToValueOrNull<T>(node : TreeNode) : T?
= try { treeToValue(node, T::class.java) }
catch (ex : Exception) { null }
这是有效的,因为在 Kotlin 中,try
-catch
-statements 可以有一个返回值。现在,您可以使用 when
来处理 json:
lateinit var object : Any
when {
mapper.treeToValueOrNull<ClassA>(jsonNodeObj)?.let { object = it } != null
-> dosthA(object as ClassA)
mapper.treeToValueOrNull<ClassB>(jsonNodeObj)?.let { object = it } != null
-> dosthB(object as ClassB)
mapper.treeToValueOrNull<ClassC>(jsonNodeObj)?.let { object = it } != null
-> dosthC(object as ClassC)
}
pdvrieze found an even shorter solution :
val object = mapper.treeToValueOrNull<ClassA>(jsonNodeObj)
?: mapper.treeToValueOrNull<ClassB>(jsonNodeObj)
?: mapper.treeToValueOrNull<ClassC>(jsonNodeObj)
关于json - 在 kotlin 中分支 json 解析的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48194303/