Kotlin Jackson Mapper将String反序列化为HashMap <string,any =“”>而不是type

时间:2019-02-07 15:51:14

标签: java generics kotlin jackson

我定义了一个方法:

protected inline fun <reified T : Any> executeForEntity(httpUriRequest: HttpUriRequest): T {
    return httpClient.execute(httpUriRequest) { response: HttpResponse ->
        val status = response.statusLine.statusCode
        if (status == 200) {
            val content = EntityUtils.toString(response.entity)
            // this is the Jackson default readValue()
            objectMapper.readValue(content, T::class.java)
        } else {
            throw RuntimeException("Service error occurred, status=${response.statusLine.statusCode}, content=${EntityUtils.toString(response.entity)}")
        }
    }
}

我正在尝试:

val entities: List<Entity> = getForEntity("/api/v1/my-entities")

但是,Jackson没有获得实体列表,而是返回了HashMaps的ArrayList?即使使用显式类型声明,这也发生了什么奇怪的事情?

使用杰克逊·科特林模块的扩展方法会使错误更加严重。这些用例不支持泛型吗?

1 个答案:

答案 0 :(得分:1)

您可以像这样使用TypeReference

objectMapper.readValue<T>(json, object : TypeReference<T>() {})