由于项目的工程上面输出json到前段有部分信息为null值,所以在网上找了点方法将null转换为空字符串的方法。
1、建立一个新的类JsonObjectMapper用于处理json的转换。
package com.xjj.anes.mvc.converter;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* @description: 转换null对象为空字符串
*/
public class JsonObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
public JsonObjectMapper() {
super();
// 允许单引号
this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 字段和值都加引号
this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 数字也加引号
this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
jg.writeString("");
}
});
}
}
2、spring-mvc.xml配置文件中的mvc:annotation-driven添加如下内容
<!-- 注册RequestMappingHandlerMapping 和RequestMappingHandlerAdapter 两个bean。-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.xjj.anes.mvc.converter.JsonObjectMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
参考文章:
http://blog.csdn.net/clementad/article/details/42169049
http://m.w2bc.com/article/175979