若需要对 Jackson 的序列化行为进行定制,比如,排除值为空属性、进行缩进输出、将驼峰转为下划线、进行日期格式化等,这又如何实现呢?
首先,我们需要扩展 Jackson 提供的 ObjectMapper 类,代码如下:
public class CustomObjectMapper extends ObjectMapper {
private boolean camelCaseToLowerCaseWithUnderscores = false;
private String dateFormatPattern;
public void setCamelCaseToLowerCaseWithUnderscores(boolean camelCaseToLowerCaseWithUnderscores) {
this.camelCaseToLowerCaseWithUnderscores = camelCaseToLowerCaseWithUnderscores;
}
public void setDateFormatPattern(String dateFormatPattern) {
this.dateFormatPattern = dateFormatPattern;
}
public void init() {
// 排除值为空属性
setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 进行缩进输出
configure(SerializationFeature.INDENT_OUTPUT, true);
// 将驼峰转为下划线
if (camelCaseToLowerCaseWithUnderscores) {
setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
// 进行日期格式化
if (StringUtil.isNotEmpty(dateFormatPattern)) {
DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern);
setDateFormat(dateFormat);
}
}
}
然后,将 CustomObjectMapper 注入到 MappingJackson2HttpMessageConverter 中,Spring 配置如下: