我有一个POJO,我试图通过以下方式使用Include.NOT_EMPTY
注释来排除空字段。
更新了完整代码
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Items {
/**
*
*/
@JsonProperty("items")
private List<Item> items = new ArrayList<Item>();
private Map<String, Object> additionalProperties =
new HashMap<String, Object>();
/**
*
* @return
* The items
*/
@JsonProperty("items")
public List<item> getItems() {
return items;
}
/**
*
* @param items
* The items
*/
@JsonProperty("items")
public void setitems(List<Item> items) {
this.items = items;
}
@JsonAnyGetter
@JsonUnwrapped
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
但是,当我打印出JSON时,我会以下列方式得到回复。
{ "items": [
{...}],
"additionalProperties": { } // I expect this to be removed.
}
知道我在这里做错了吗? 如果重要,我会使用Jackson-core 2.1.1。
答案 0 :(得分:2)
您需要在Class级别添加它
@JsonInclude(Include.NON_EMPTY)
以下代码可以正常使用
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
String [] characteristics = new String[]{};
Employee emp = new Employee("John", "20", "Male", characteristics);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
mapper.writeValue(System.out, emp);
}
class Employee {
String name;
String age;
String gender;
String [] characteristics;
//setters and getters
}
输出:{"name":"John","age":"20","gender":"Male"}
答案 1 :(得分:0)
您可以像下面的additionalProperties setter和property一样更改代码,并在类级别使用@JsonInclude(Include.NON_NULL)
private Map<String, Object> additionalProperties = null;
public void setAdditionalProperty(String name, Object value) {
if(additionalProperties == null)
additionalProperties = new HashMap<String, Object>();
this.additionalProperties.put(name, value);
}