java - 如果我有一个复杂的响应对象,如何使用 JsonIninclude 注释忽略空值

标签 java spring spring-boot

据说我有一个如下所示的复杂对象作为我对请求的其余响应

public class emp {
     int Id;
     String Name;
     Address address;

 }

 public Class address {
    String StreetAdress1;
    StreetAdress2;
    String AptNO;
    String Zip;
    String State;
    String Country;
  }

我只是想忽略 empAddress 类中的 null

我的问题是,如果我在 emp 类上使用 JsonInclude ,这将有助于在作为 json 响应发送回时丢弃地址类中的 null .

我还没有尝试过,只是心里有一个问题,想问一下这是否可行。

如何使用复杂 Json

最佳答案

如果您使用 Jackson,则可以使用 JsonInclude 注释来实现:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Address {
    private String streetAdress1;
    private String aptNO;
    private String zip;
    private String state;
    private String country;
    // setter and getter
}

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        Address address = new Address();
        address.setCountry("some-country");
        ObjectMapper mapper = new ObjectMapper();
        String       json   = mapper.writeValueAsString(address);
        System.out.println(json);
    }
}

结果:

{
    "country":"some-country"
}

关于java - 如果我有一个复杂的响应对象,如何使用 JsonIninclude 注释忽略空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162882/

相关文章:

java - Spring Error Controller 响应 Not Acceptable

java - Spring Boot不会在MySQL中创建表

java - 使用 swing 布局具有多个自定义组件的 jpanel

java - 从 Xalan 捕获异常

java - 序列化具有不可序列化父类的对象

java - 什么时候在 Spring 中使用 ModelAndView 和 Model?

java - Spring : injecting data object in service

java - 如何在运行时在方法中 Autowiring 类

java - 了解 spring-security-oauth2 @EnableAuthorizationServer

java - 如何在Spring boot中加载没有任何文件扩展名的配置文件