@JsonInclude(Ininclude.NON_NULL) 如何在 Spring Boot 中工作

Ale*_*Dev 6 java spring spring-mvc jackson spring-boot

我试图了解 @JsonIninclude 存在的原因是什么,以便在我的 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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

A代码B代码之间的唯一区别是B代码中的greeting类没有使用@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
Run Code Online (Sandbox Code Playgroud)

得到同样的行为,那么使用@JsonInclude注解有什么用处呢?

例如,我预计在A 代码中,当我发送仅包含一个字段的请求时,如下所示:

~ curl -H "Content-Type: application/json" -X POST localhost:8080  -d '{"name": "AlejoDev"}'
Run Code Online (Sandbox Code Playgroud)

Greeting 对象 变成了只有一个字段的对象,而不是有两个字段的对象。一满一空。

Yog*_*h_D 10

该注释的意思是当一个对象被反序列化时是否只包含非空字段。

当您将它用于作为输入获取的对象时,即使输入字段为 null,因为变量nameemail 是类级别字段,它们也会被初始化为默认值 null。

因此,当您创建 return 语句时,您总是会得到 null。

尝试使用 JSON 对象作为响应来使用此注释,然后尝试填充一些字段并将一些字段保留为空,然后查看对各种调用的响应。这将帮助您了解此注释的效果。