kotlin数据类HttpMessageNotReadableException

时间:2017-09-20 14:28:11

标签: json spring kotlin

我和邮递员一起尝试这个代码,但没有任何作用,为什么?

我发送的内容:

{
    "name":"front_msel",
    "gitlabId": "83",
    "fichierVersion":"VERSION"
}

我的弹簧控制器:

@RestController
@RequestMapping("/projects")
class ProjectController(val projectRepository: ProjectRepository) {
    private val log = LoggerFactory.getLogger(ProjectController::class.java)

    @PostMapping()
    fun saveProject(@RequestBody payload: Project): String {
        log.info("project: '{}'", payload.toString())
       return projectRepository.save(payload).gitlabId?:"-1"
    }

}

我得到了什么:

{
"timestamp": 1505917417221,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of com.......model.Project: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.......model.Project: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@66ba61d9; line: 2, column: 2]",
"path": "/projects"

}

我的项目数据类:

data class Project(val name:String?, val gitlabId: String?, val fichierVersion: String?)

我加倍检查参数,这不是措辞错误,这些东西不起作用?

编辑:

感谢Todd,问题是通过向我的param添加null值来解决问题,以生成零参数构造函数。谢谢!

data class Project(val name:String? = null, val gitlabId: String? = null, val fichierVersion: String? = null)

1 个答案:

答案 0 :(得分:2)

我通过稍微改动来实现这一点。

首先,由于您的所有Project字段都可以为空,因此请提供默认值,以便编译器生成零参数构造函数:

data class Project(val name:String? = null, val gitlabId: String? = null, val fichierVersion: String? = null)

其次,Spring似乎希望您的字段位于snakey_case而不是camelCase,因此请将有效负载更改为:

{
  "name":"front_msel",
  "gitlab_id": "83",
  "fichier_version":"VERSION"
}