据说我有一个如下所示的复杂对象作为我对请求的其余响应
public class emp {
int Id;
String Name;
Address address;
}
public Class address {
String StreetAdress1;
StreetAdress2;
String AptNO;
String Zip;
String State;
String Country;
}
我只是想忽略 emp
和 Address
类中的 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/