shr*_*ing 3 spring spring-boot
我有一个像这样的 DTO 对象:
data class ClientDto(
var uuid: String,
var ip: String,
var lastSeen: Date? = Date()
) {
internal fun toEntity() = Client(uuid=uuid, ip=ip, lastSeen=Date())
}
Run Code Online (Sandbox Code Playgroud)
...和这样的控制器:
@RestController
internal class ClientController {
@Autowired
private lateinit var service : ClientService
@GetMapping("/clients")
internal fun getClients() = service.findAll()
@PostMapping("/clients")
internal fun postClient(@RequestBody client: ClientDto) = service.add(client)
}
Run Code Online (Sandbox Code Playgroud)
现在我用 httpie 发帖是这样的:
http POST localhost:8080/clients uuid=my-uuid ip=192.123.31:8080
Run Code Online (Sandbox Code Playgroud)
并得到:
{
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of awesome.discovery.domain.dto.ClientDto: 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 awesome.discovery.domain.dto.ClientDto: 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@71c6ae97; line: 1, column: 2]",
"path": "/clients",
"status": 400,
"timestamp": 1519587678605
}
Run Code Online (Sandbox Code Playgroud)
1- 你的 DTO 需要提供一个默认构造函数(没有参数的空构造函数)。这是错误所说的
2-Spring 将 Jackson 配置为根据 .json 文件的类型使用反射来自动反序列化 JSON RequestParam。您可以自定义此行为实现JsonDeserializer. 如果要调试,可以在注释的方法上放置断点PostMapping
| 归档时间: |
|
| 查看次数: |
2660 次 |
| 最近记录: |