我的问题很简单,Jackson2ObjectMapperBuilder只能用于响应的序列化,而不能用于请求的序列化吗?
谢谢!
答案 0 :(得分:1)
您的问题的答案是:不,杰克逊可以将JSON反序列化为对象,并将对象序列化回JSON。它是一个非常强大的图书馆。
您应首先澄清您所看到的行为和预期的行为,以便更容易了解正在发生的事情。
我能给你的最简单的代码是:
class DemoApplication {
static void main(String[] args) {
SpringApplication.run DemoApplication, args
}
@PostMapping("/")
String greet(@RequestBody Greeting greeting) {
return "Hello ${greeting.name}, with email ${greeting.email}"
}
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Greeting {
String name
String email
}
对该端点的一些简单的CURL请求:
~ curl -H "Content-Type: application/json" -X POST localhost:8080
{"timestamp":"2018-04-22T21:18:39.849+0000","status":400,"error":"Bad Request","message":"Required request body is missing: public java.lang.String com.example.demo.DemoApplication.greet(com.example.demo.Greeting)","path":"/"}
~ curl -H "Content-Type: application/json" -X POST localhost:8080 -d '{}'
Hello null, with email null
~ curl -H "Content-Type: application/json" -X POST localhost:8080 -d '{"name": "AlejoDev"}'
Hello AlejoDev, with email null
~ curl -H "Content-Type: application/json" -X POST localhost:8080 -d '{"name": "AlejoDev", "email":"info@alejodev.com"}'
Hello AlejoDev, with email info@alejodev.com
因此,当不发送数据时,Spring会将异常发送回客户端,错误代码为400(错误请求)。
其他任何事情(发送一个空对象或其上的数据)都可以正常工作,在需要时将字段设置为null。
你可以发布你的代码吗?