Original blog: https://www.cnblogs.com/yangy608/p/3936848.html
1. entities
/** * The marked on the attribute, the attribute is NULL if not involved in the sequence of * If the top in the class, and that all the properties of this class of work * Include.Include.ALWAYS 默认 * Include.NON_DEFAULT not attribute to the default value of the sequence * Include.NON_EMPTY property is empty ( "") is NULL or not serialized * Include.NON_NULL property is not serialized NULL */ @JsonInclude(Include.NON_NULL)
2. On the code
ObjectMapper mapper = new ObjectMapper(); /** * Set the mapper objects through this method, all the objects will be serialized serialized change rules * Include.Include.ALWAYS 默认 * Include.NON_DEFAULT not attribute to the default value of the sequence * Include.NON_EMPTY property is empty ( "") is NULL or not serialized * Include.NON_NULL property is not serialized NULL */ mapper.setSerializationInclusion(Include.NON_NULL); User user = new User(1,"",null); String outJson = mapper.writeValueAsString(user); System.out.println(outJson);
Note: Only for VO work, Map List does not work, for example:
ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); Map map = new HashMap(); map.put("a", null); map.put("b", "b"); String ret_val = mapper.writeValueAsString(map); System.err.println (ret_val); Map m = mapper.readValue(ret_val, Map.class); System.err.println(m.get("a") + "|" + m.get("b"));
Output:
{
"b"
:
"b"
,
"a"
:
null
}
null
|b
VO = the new VO (); vo.setA ( null ); vo.setB("b"); String ret_val1 = mapper.writeValueAsString(vo); System.err.println (ret_val1); VO v = mapper.readValue (ret_val1, VO. Class ); System.err.println(v.getA() + "|" + v.getB());<br>
Output:
{
"b"
:
"b"
}
|b