Jackson ObjectMapper序列化时保留空字符串的配置问题咨询
问题描述
我有如下JSON对象 payload:
{"phoneNumbers": [{"id": 1,"number": "01234 567 890",},{"id": 2,"number": "",}]}
对应的Java序列化方法如下:
public String getJson(Object object) { String result = null; try { result = objectMapper.writeValueAsString(object); } catch (IOException e) { logger.error(e.getMessage(), e); } return result; }
通过构造函数注入并配置Jackson的ObjectMapper:
@Autowired public ServiceImpl(@Qualifier("objectMapper") ObjectMapper objectMapper) { this.objectMapper = objectMapper; configureObjectMapper(objectMapper); }
配置方法:
private static void configureObjectMapper(ObjectMapper objectMapper) { objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDateFormat(new SimpleDateFormat(DATE_PATTERN)); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.setSerializationInclusion(Include.NON_EMPTY); }
调用writeValueAsString时,Jackson会忽略第二个对象里的空字符串number字段,返回结果如下:
{"phoneNumbers": [{"id": 1,"number": "01234567890",},{"id": 2,}]}
但改用Codehaus的ObjectMapper实例时:
public String getJson(Object object) { org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper() .configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); String result = null; try { result = objectMapper.writeValueAsString(object); } catch (IOException e) { logger.error(e.getMessage(), e); } return result; }
它不会忽略空字符串,这正是我想要的效果。我使用的是Jackson-core 2.14.0版本,试了多种配置都没解决,求正确的Jackson配置方法,让空字符串""能正常序列化不被忽略。
解决方案
问题出在你设置的序列化包含规则上:
objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.setSerializationInclusion(Include.NON_EMPTY);
连续调用两次setSerializationInclusion后,最终生效的是后者Include.NON_EMPTY,而该规则会将空字符串视为“空值”进行忽略。
要保留空字符串,可按以下两种方式调整配置:
- 仅排除null值:如果只需要忽略
null字段,保留空字符串、空集合等,直接移除Include.NON_EMPTY的设置,只保留Include.NON_NULL:
private static void configureObjectMapper(ObjectMapper objectMapper) { objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDateFormat(new SimpleDateFormat(DATE_PATTERN)); objectMapper.setSerializationInclusion(Include.NON_NULL); }
- 精细组合规则:如果需要排除
null值和空集合/数组,但保留空字符串,可使用JsonInclude.Value组合规则:
private static void configureObjectMapper(ObjectMapper objectMapper) { objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDateFormat(new SimpleDateFormat(DATE_PATTERN)); // 排除null值,空字符串保留,空集合/数组排除 objectMapper.setSerializationInclusion(JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_EMPTY )); }
注:Include.NON_EMPTY的默认逻辑是:字符串空值会被忽略,空集合/数组会被忽略,空对象则受FAIL_ON_EMPTY_BEANS配置控制。因此要保留空字符串,最直接的方式就是不要设置Include.NON_EMPTY。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

