如果希望属性值为null及不序列化,只序列化不为null的值。
1、测试代码
配置代码:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
或者通过注解@JsonInclude(JsonInclude.Include.NON_NULL)
//常见问题2:属性为null,不序列化
@RequestMapping("/commonQuestion2")
@ResponseBody
public void commonQuestion1() throws Exception{
ObjectMapper mapper = new ObjectMapper();
Student student=new Student("1001",null);
//属性为null不参与序列化
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//将字符串转换为对象
String param= mapper.writeValueAsString(student);
System.out.println("===null值不参与序列化==="+param);
}
输出结果:
本文介绍了如何在Java中使用JacksonObjectMapper进行序列化时控制null值的处理,通过设置JsonInclude.Include.NON_NULL策略,只有非null的属性才会被序列化到JSON中。作者给出了一个示例,展示了如何在Student对象中处理null属性并输出结果。
1107

被折叠的 条评论
为什么被折叠?



