我正在尝试在我的新的springboot应用程序中使用Ktorm,并在尝试使用Ktorm实体接口作为trying启动控制器参数时遇到问题。
实体和控制器如下所示:
// Controller definition
@RestController
class TaskController() {
@PostMapping
fun addTask(
@RequestBody task: Task
): Long {
// ... do something with `task`
}
}
// Entity definition (unncessary properties are omitted)
interface Task : Entity<Task> {
var id: Long
var title: String
var content: String
companion object : Entity.Factory<Task>()
}一旦调用函数addTask(),我就得到了这个异常
HttpMessageConversionException类型定义错误:简单类型,类website.smsqo.entity.Task;嵌套异常是:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException无法构造website.smsqo.entity.Task的实例(与默认构造函数一样,不存在任何创建者):
抽象类型需要映射到具体类型,具有自定义反序列化程序,或者在Source:(PushbackInputStream)处包含附加类型信息\n;行: 1,列: 1“}
(Paramter task是由RequestBody从前端发布的)
我认为原因可能是,作为一个接口,springboot无法找到一种正确的方法来初始化Task。但是,将其重构到这一点肯定不是一个优雅的解决方案:
@RestController
class TaskController() {
@PostMapping
fun addTask(
id: Long, title: String, content: String // even more fields...
): Long {
val task = Task {
this.id = id
this.title = title
this.content = content
}
// ... do something with `task`
}
}有没有更好的解决方案?谢谢您的提前回复!
发布于 2021-12-02 07:44:28
事实上,Ktorm提供的文件明确指出了解决方案:
// extracted from org.ktorm.entity.Entity
/*
* Besides of JDK serialization, the ktorm-jackson module also supports serializing entities in JSON format. This
* module provides an extension for Jackson, the famous JSON framework in Java word. It supports serializing entity
* objects into JSON format and parsing JSONs as entity objects. More details can be found in its documentation.
*/实现org.ktorm:ktorm-jackson:3.4.1带来了一个杰克逊模块,名为KtormModule in package org.ktorm.jackson。接下来我们需要做的是将模块应用于我们的springboot应用程序,就像@Configuration注释的类中那样:
@Configuration
class KtormConfig {
@Bean
fun ktormJacksonModule(): Module = KtormModule()
// ... and other configurations if you like
}就是这样。这样的KtormModule将在springboot应用程序启动时被杰克逊发现和应用,之后json和Ktorm实体之间就不会再有编码和解码问题了。
https://stackoverflow.com/questions/70151402
复制相似问题