java springMVC json序列化配置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 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);
		}
	}
}

以上是关于java springMVC json序列化配置的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC--10配置过滤器以及Json

SpringMVC--10配置过滤器以及Json

SpringMVC--10配置过滤器以及Json

springMVC是如何实现参数封装和自动返回Json的

HttpMessageConverter

SpringMVC Json自定义序列化和反序列化