---
title: "自定义全局jackson序列化"
author: "hepx"
date: "2013-06-24T11:49:46Z"
tags: []
categories: ["开源软件"]
slug: "jackson"
draft: false
lastmod: "2013-06-24T11:49:46Z"
id: 1893265
url: "https://hepx.iteye.com/blog/1893265"
---

描述在WEB开发中前后台使用JSON传输，难免前后台格式的转换的问题。以下是以SPRINGMVC开发为例说明

如：日期的转换；null的转换等

 

1：自定义一个继承ObjectMapper的类

```
/**
 * 自定义的JSON转换MAPPER
 * @author xixi
 * @date 2013-6-24
 *
 */
public class CustomObjectMapper extends ObjectMapper {

	public CustomObjectMapper(){
		super();
		//设置null转换""
		getSerializerProvider().setNullValueSerializer(new NullSerializer());
		//设置日期转换yyyy-MM-dd HH:mm:ss
		setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}
	
	//null的JSON序列
	private class NullSerializer extends JsonSerializer<Object> {
		public void serialize(Object value, JsonGenerator jgen,
				SerializerProvider provider) throws IOException,
				JsonProcessingException {
			jgen.writeString("");
		}
	}
}
```

 2：在spring的配置文件中定义这个自定义的Mapper

```
	<!-- 启动 MVC注解 -->
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
				<property name="objectMapper" ref="customObjectMapper" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- 自定义的JSON ObjectMapper -->
	<bean id="customObjectMapper" class="com.xixi.web4j.util.CustomObjectMapper" />
```

 就这么简单，不用再像每个POJO对像上去@JsonSerializer(using...)了。

以后对所有DATE类型字段序列化JSON，都会默认传为“yyyy-MM-dd HH:mm:ss”格式，对于字段为null的也会转为“”。如果你对null有别的处理。你可以在自定义的NullSerializer修改你想要的格式。