【问题标题】:Kotlin Jackson Mapper deserializing String as HashMap<String, Any> instead of typeKotlin Jackson Mapper 将字符串反序列化为 HashMap<String, Any> 而不是类型
【发布时间】:2019-02-07 15:51:14
【问题描述】:

我定义了一个方法:

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 没有得到实体列表,而是返回了 HashMap 的 ArrayList?即使有明确的类型声明......这很奇怪,发生了什么?

使用 jackson kotlin 模块的扩展方法会使错误更加严重。这些用例不支持泛型吗?

【问题讨论】:

  • 您需要提供Class&lt;T&gt; clazz 作为第二个参数并提供它。
  • 不幸的是,这个“T”可能是一个集合,而 Java 类型擦除使这成为不可能

标签: java generics kotlin jackson


【解决方案1】:

你可以像这样使用TypeReference

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多