您的问题的答案是:不,Jackson 可以将 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 (Bad Request)。
其他任何东西(发送一个空对象或上面的数据)都可以正常工作,在需要时将字段设置为 null。
你能发布你的代码吗?