我正在尝试使用Jackson库1.5创建一个Json对象,但也获得了具有Null值的对象。
如何摆脱Null值?
以下是我正在使用的代码。
package com.test;
public class Sample {
public String name;
public String surname;
public Sample(String name, String surname) {
this.name = name;
this.surname = surname;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
}
public static void main(String[] args){
Sample sample = new Sample("Sam", null);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
System.out.println(mapper.writeValueAsString(restRetrieveQuoteResponse));
}
}
这里的问题是mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
不推荐使用WRITE_NULL_PROPERTIES。
我试图找到替代方案,但找不到。大多数可用的解决方案都是使用Jackson 2.2。有人可以帮我解决1.5吗?
答案 0 :(得分:3)
答案 1 :(得分:2)
尝试使用
mapper.setSerializationInclusion(Include.NON_NULL);
答案 2 :(得分:1)
答案 3 :(得分:1)
macziknasz中的链接回答需要登录,所以我只是在这里发布我的解决方案:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);