TheOldDriver
8/26/2017 - 3:56 AM

springMVC json序列化配置

springMVC json序列化配置

<!-- 自定义定制jackson序列化,时间格式化,参数校验 -->
<mvc:annotation-driven>
	<mvc:message-converters>
		<bean class="org.springframework.http.converter.json.
		  MappingJackson2HttpMessageConverter">
			<property name="objectMapper" ref="objectMapper" />
		</bean>
	</mvc:message-converters>
</mvc:annotation-driven>

<bean id="objectMapper" class="org.spring.sample.configration.CustomObjectMapper" init-method="init">  
    <property name="camelCaseToLowerCaseWithUnderscores" value="true"/>  
    <property name="dateFormatPattern" value="yyyy-MM-dd HH:mm:ss"/>  
</bean>
//配置json序列化java
package org.spring.sample.configration;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;

public class CustomObjectMapper extends ObjectMapper {
	private static final long serialVersionUID = 1L;
	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() {
		// 设置null值不参与序列化(字段不被显示)
		this.setSerializationInclusion(Include.NON_NULL);
		// 禁用空对象转换json校验
		this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		// 进行缩进输出
		configure(SerializationFeature.INDENT_OUTPUT, true);
		// 将驼峰转为下划线
		if (camelCaseToLowerCaseWithUnderscores) {
			setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		}
		// 进行日期格式化
		if (!StringUtils.isEmpty(dateFormatPattern)) {
			DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern);
			setDateFormat(dateFormat);
		}
	}
}