【问题标题】:How @JsonInclude(Include.NON_NULL) works In Spring Boot@JsonInclude(Include.NON_NULL) 如何在 Spring Boot 中工作
【发布时间】: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


    【解决方案1】:

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

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

    因此,当您创建您的 return 语句时,您总是会为那些返回 null。

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

    【讨论】:

      【解决方案2】:

      @JsonInclude(Include.NON_NULL)@JsonInclude(JsonInclude.Include.NON_NULL) 用于忽略对象中的空字段。 在您的特定示例中,您返回了一个 String 值,这就是它打印 null 的原因。 如果你尝试返回完整的对象,那么你会发现响应体中没有包含空字段

      【讨论】:

        猜你喜欢
        • 2015-03-13
        • 2020-04-09
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        • 2017-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多