jackson:SerializationConfig.Feature 的枚举常量 WRITE_NULL_MAP_VALUES

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.TypeReference;

public abstract class JsonMapper {
private static final Logger logger = LoggerFactory
.getLogger(JsonMapper.class);
private static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
// 设置输出:包含的属性不能为空  
mapper.getSerializationConfig().setSerializationInclusion(
Inclusion.NON_NULL);
// 设置输入:禁止把POJO中值为null的字段映射到json字符串中
mapper.getSerializationConfig().disable(Feature.WRITE_NULL_MAP_VALUES);
}

/**
* 将Json字符串转化成指定的Java对象,不包括泛型的集合类

* @param json
*            Json字符串
* @param clazz
*            转换Java目标类
* @return
*/
public static T toObject(String json, Class clazz) {
T object = null;
try {
object = mapper.readValue(json, clazz);
return object;
} catch (Exception ex) {
logger.error("from json to Object error", ex);
}
return object;
}

}

参考:

http://stackoverflow.com/questions/3140563/how-to-avoid-null-values-serialization-in-hashmap

I would like to serialize a HashMap as a string through the Jackson JSON processor. For example:

String strMap = getMapper().writeValueAsString(myHashMap);
result output -> {"r_id":6,"a_am":null,"smb":"Submit","a_li":null,"l_id":878,"pos":[1345,1346,1347]}

I don't know how to disable null values serialization for Map. It works fine only for POJO if configure the Jackson like this:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

For what it's worth, Jackson 1.6 will have this:

objectMapper.configure(SerializationConfig.WRITE_NULL_MAP_VALUES, false);

which does do what you want. Existing method only works for beans, and is not being changed to ensure maximum backwards compatibility.

Or you can annotate your bean with @JsonWriteNullProperties(false) which will

API:

http://jackson.codehaus.org/1.8.8/javadoc/index.html

你可能感兴趣的:(java工具)