我相信您可以将结果定义为com.fasterxml.jackson.databind.JsonNode的实例。
data class Result(
val results: JsonNode
)
然后您可以根据 results 的类型来处理它 - 无论是 ArrayNode 还是 ObjectNode(两者都扩展 JsonNode):
fun processResults(results: JsonNode) = when{
results.isArray -> processArrayNode(results)
else -> processObjectNode(results)
}
private fun processArrayNode(list: JsonNode): *return whatever you need*{
val elements = list
.elements()
.asSequence()
.toList()
val mappedElements = elements.map{
processObjectNode(it)
}
// do whatever you need with the array
}
private fun processObjectNode(person: JsonNode): *return whatever you need*{
//** this will transform the json node into a linkedHashMap where the keys are the json keys and the values are the values (here interpreted as jsonNodes) **/
val fieldsMap = person
.fields()
.asSequence()
.associateBy( {it.key}, {it.value} )
// process whatever you need
}
这是对两个 API 调用使用相同 DTO 的一种方法。在我看来,额外的工作是不值得的。我将创建两个包含results 字段的DTO,其中一个是Person 的实例,另一个是List<Person> 的实例。
编辑:对上述 sn-p 的一个小升级是向 JsonNode 添加扩展方法:
fun JsonNode.elementsToList(): List<JsonNode> = this
.elements()
.asSequence()
.toList()
fun JsonNode.fieldsToMap(): Map<String, JsonNode> = this
.fields()
.asSequence()
.associateBy({it.key}, {it.value})