本文主要介绍Java使用Jackson来序列化Joda DateTime时间日期的自定义格式的方法及代码,和Jackson的Maven的pom.xml文件。

1、使用Maven引用Jackson

pom.xml增加如下配置:

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.5.4</version>
</dependency>

2、使用自定义序列化器CustomDateSerializer

1)在需要的格式化时间的对象

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

2)自定义序列化器CustomDateSerializer

public class CustomDateSerializer extends JsonSerializer<DateTime> {
private static DateTimeFormatter formatter =
DateTimeFormat.forPattern("dd-MM-yyyy");
@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
}
}

3、通过JodaModule使用默认时间日期格式

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

4、通过CustomObjectMapper实现

1)对象映射器执行全局配置

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

2)自定义映射器CustomObjectMapper

public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
}
}

5、使用@JsonFormat实现定义时间日期格式

1)在序列化对象的方法上使用@JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
return date;
}

2)使用ObjectMapper序列化

   ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ObjectWriter ow = mapper.writer();
try {
String logStr = ow.writeValueAsString(log);
outLogger.info(logStr);
} catch (IOException e) {
logger.warn("JSON mapping exception", e);
}