spring mvc3 jackson输出null值处理

spring mvc3 jackson输出null值转为空串,找了很久终于找到办法

spring-mvc.xml中配置:
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
	class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
	<property name="supportedMediaTypes">
		<list>
			<value>text/html;charset=UTF-8</value>
			<value>application/json;charset=UTF-8</value>
		</list>
		</property>

	<!-- 处理json中null值,展示为""(空串) -->
	<property name="objectMapper">
		<bean class="com.tyrbl.zy.utils.spring.ObjectMappingCustomer"></bean>
	</property>
</bean>
	
<!-- 启动Spring MVC 的注解功能,完成请求和注解POJO的映射 -->
<bean
	class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	<property name="messageConverters">
		<list>
			<!-- json转换器 -->
			<ref bean="mappingJacksonHttpMessageConverter" />
  		</list>
	</property>
</bean>


objectMapper类:
package com.tyrbl.zy.utils.spring;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;

public class ObjectMappingCustomer extends ObjectMapper {

	public ObjectMappingCustomer() {
		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("");
					}
				});

	}
}

猜你喜欢

转载自blueskyrh.iteye.com/blog/2144479