【问题标题】:Spring Jackson Databind does not work for my Kotlin data classSpring Jackson Databind 不适用于我的 Kotlin 数据类
【发布时间】:2020-05-01 04:08:09
【问题描述】:

当使用 Spring 的 RestTemplate 将一些 JSON 响应反序列化为对象时,我没有这样做,因为我使用 Kotlin 数据类作为我的对象模型。

这是数据类:

data class Description (
        val descriptionShort: String,
        val descriptionLong: String,
        val productGroupName: String,
        val shortDescriptionProductGroup: String,
        val descriptionProductGroupMarketing: String
)

我使用这些依赖项:

    dependencies {
        implementation("org.springframework.boot:spring-boot-starter-webflux")
        //others
    }

    dependencyManagement {
        imports {
            mavenBom("org.springframework.boot:spring-boot-dependencies:2.2.0.RELEASE")
            //others
        }
        dependencies {
            dependency("org.springframework.cloud:spring-cloud-stream-reactive:2.2.1.RELEASE")
            dependency("com.fasterxml.jackson.module:jackson-module-kotlin:2.10.2")
            //others

        }
    }

执行涉及 RestTemplate 逻辑的单元测试时的错误信息:

原因:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造com.company.importer.customer.converter.ut.Description 的实例(没有像默认构造一样的创建者):无法从对象值反序列化(没有基于委托或基于属性的创建者)

【问题讨论】:

    标签: spring kotlin jackson


    【解决方案1】:

    一位朋友告诉我需要一个无参数构造函数。 这是在 Kotlin 中通过给每个属性一个默认值来完成的:

    data class Description (
            val descriptionShort: String = "",
            val descriptionLong: String = "",
            val productGroupName: String = "",
            val shortDescriptionProductGroup: String = "",
            val descriptionProductGroupMarketing: String = ""
    )
    
    

    【讨论】:

      【解决方案2】:

      很多天前我遇到了类似的问题;作为第一步,我在@xetra11 的回复中解决了这个问题,但我对仅出于技术原因使用默认值的想法并不满意。

      最后我解决了我的问题,只需将@RequestBody 注释添加到控制器的方法参数:我​​的方法现在看起来像

      fun newTransaction(@RequestBody input: NewTxRequest)
      

      NewTxRequest定义如下

      data class NewTxRequest(val from: String, val to: String, val amount: BigDecimal)
      

      并且序列化工作正常......我希望这也可以帮助你!

      【讨论】:

      • 有趣但不幸的是我的逻辑不是使用控制器而是使用http客户端,因此我无法使用@RequestBody
      • 你能显示你正在反序列化的代码吗?
      • ``` final ResponseEntity exchange = restTemplate .exchange(EVALUATE_PRODUCT_PATH + catalogId, HttpMethod.POST, request, Description.class);```
      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 2018-04-19
      • 2019-08-13
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2018-06-07
      • 2020-11-06
      相关资源
      最近更新 更多