我试图了解@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"}'
问候对象 成为只有一个字段的对象,而不是具有两个字段的对象。一个满,一个空。
答案 0 :(得分:1)
该注释的含义是,当反序列化对象时,是否仅包含非空字段。
当您将它作为输入使用的对象时,即使输入字段为空,因为变量function_char_format = str_replace("dnorm(0,1),.,"r") %>%
str_replace(".","r") %>%
str_replace("\\(","(1e4, ") #this returns "rnorm(100,0,1)"
execute_function??(function_char_format)
和name
是类级字段,它们将被输入到它们的默认值为null。
因此,当您创建return语句时,您将始终为这些语句获取null。
尝试使用JSON对象作为响应的此注释,然后尝试填充一些字段并将某些字段保留为null,然后查看对各种调用的响应。这有助于您了解此注释的效果。
答案 1 :(得分:1)
@JsonInclude(Include.NON_NULL)或 @JsonInclude(JsonInclude.Include.NON_NULL) 用于忽略对象中的空字段。 在您的特定示例中,您返回了一个String值,这就是它打印null的原因。 如果您尝试返回完整对象,则会发现响应正文中不包含空字段