有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

例如,我有一个复杂的对象,如下所示,作为对请求的rest响应

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响应发送回时,是否有助于丢弃address类中的null

我还没有试过,只是脑子里有个问题,想问一下这样是否行得通

如何使用复杂的Json


共 (2) 个答案

  1. # 1 楼答案

    如果您正在使用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"
    }
    
  2. # 2 楼答案

    要回答这个问题,

    当我尝试@JsonInclude(JsonInclude.Include.NON_EMPTY)时,它正在检查null和EMPTY