背景介绍
在前端通过json格式传递参数,后端使用@RequestBody方式接收参数的场景下,经常需要将空字符串反序列化成null,以避免进行冗余的逻辑处理。
本文通过不同类型的场景,分别进行说明。
所需要反序列化的java对象如下:
@Getter
@Setter
@ToString
public class TestBean { 
    private String name;
    private String phone;
    private Address address;
}
对于String类型的应用
- 给定的json字符串如下,期望能够将phone属性值映射为null
 
{ "name":"zhangsan","phone":""}
- 配置方式如下,该配置全局有效
 
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StdDeserializer<String>(String.class) { 
    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { 
        String result = StringDeserializer.instance.deserialize(p, ctxt);
        if (StringUtils.isEmpty(result)) { 
            return null;
        }
        return result;
    }
});
mapper.registerModule(module);
对于另外一种使用自定义反序列化类的用法,每次使用时都需要在字段上手动配置,不再赘述,可参考已有文章 json反序列化把空字符串转为null
对于POJOs类型(广义上)的应用
- 给定的json字符串如下,期望能够将address属性值映射为null,注意address的类型是POJOs
 
{ "name":"zhangsan","phone":"","address":""}
- 配置方式如下
 
ObjectMapper mapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
ACCEPT_EMPTY_STRING_AS_NULL_OBJECT的 javadoc说明如下
Feature that can be enabled to allow JSON empty String value ("") to be bound to POJOs as null.
开启该特征,能将空字符串("")对应的POJOs转换成null.
- POJOs类型的说明,常见的如自定义的class对象等
 
POJOs and other structured values (java.util.Maps, java.util.Collections),即标准POJOs和其他结构化的值,如map和collection等
注意:站在JSON格式的角度,String类型被认为是一种基本数据类型(非POJOs),因此该配置对phone字段不生效,phone字段会被映射成"",而不是null。
在SpringBoot应用中使用
在@Configuration类中加入如下配置即可
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper objectMapper() { 
	ObjectMapper mapper = new ObjectMapper();
	SimpleModule module = new SimpleModule();
	module.addDeserializer(String.class, new StdDeserializer<String>(String.class) { 
	    @Override
	    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { 
	        String result = StringDeserializer.instance.deserialize(p, ctxt);
	        if (StringUtils.isEmpty(result)) { 
	            return null;
	        }
	        return result;
	    }
	});
	mapper.registerModule(module);
	objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
	// 其他配置省略,可根据需要配置
	return objectMapper;
}
结论
- 对于String类型,使用objectMapper.registerModule(module)的方式;
 - 对于POJOs类型,使用objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)的方式;
 
参考文章
https://stackoverflow.com/questions/30841981/how-to-deserialize-a-blank-json-string-value-to-null-for-java-lang-string
https://stackoverflow.com/questions/22688713/jackson-objectmapper-deserializationconfig-feature-accept-empty-string-as-null-o
https://github.com/FasterXML/jackson-databind/issues/768
原文链接:https://blog.csdn.net/u014317046/article/details/106074794/























