【发布时间】:2018-10-03 21:57:25
【问题描述】:
我试图了解 @JsonInclude 存在的原因是什么,以便在我的 DTO 中使用它。我们来看这个简单的例子:
代码:
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_NULL)
class Greeting {
String name
String email
}
B 代码:
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}"
}
}
class Greeting {
String name
String email
}
A 代码 和 B 代码 之间的唯一区别是 B 代码 中的问候语类不使用 @JsonInclude 注释。
但如果我对该端点进行一些简单的 CURL 请求(A 代码 和 B 代码):
~ 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
获得同样的行为,那么使用@JsonInclude注解有什么用处?
例如,当我发送一个只有一个字段的请求时,我期望在A代码中,像这样:
~ curl -H "Content-Type: application/json" -X POST localhost:8080 -d '{"name": "AlejoDev"}'
Greeting 对象 变成了一个只有一个字段的对象,而不是一个有两个字段的对象。一满一空。
【问题讨论】:
标签: java spring spring-mvc spring-boot jackson