一.@JsonFormat()注解
1.需在对应日期属性上加上@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = “GMT+08”);
2.需要在每个日期属性上都得加上该标签,比较繁琐
二.@JsonSerializer()和@JsonDeserializer()使用
1. 自定义实现org.codehaus.jackson.map.JsonSerializer和
org.codehaus.jackson.map.JsonDeserializer两个类;然后通过在日期属性上添加:@JsonSerialize(using="extendsJsonSerializer");@JsonSerialize(using="extendsJsonDeserializer类")
2.自定义实现的两个类也容易写,只需实现继承而来的serialize()和deserialize()方法就行。如下:
public void serialize(Date date, JsonGenerator jsonGenerator,SerializerProvider serializerProvider) throws IOException,JsonProcessingException {
// 日期Json字符串转String格式
jsonGenerator.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date))
}
public Date deserialize(JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException,JsonProcessingException {
//字符串类型转日期类型格式
return format.parse(jsonParser.getText());
}
三、Spring的@InitBinder标签
使用SpringMVC框架进行开发时,我们可以在请求的Controller中初始化绑定日期,对日期进行转换处理.这种方式需要在每个Controller中都得加上该方法.
/*
* 日期格式化.
*/
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
}
四.继承ObjectMapper
- SpringMVC框架开发时,我们还可以通过继承ObjectMapper来实现我们自定义全局的日期转换.
public ExtendsObjectMapper() {
this.setTimeZone(TimeZone.getDefault());
CustomSerializerFactory factory = new CustomSerializerFactory();
factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider)
throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
});
}
<bean id="ExtendsObjectMapper" class="com.xx.xx.xx.converter.ExtendsObjectMapper" ></bean>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false" >
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="customerObjectMapper" ></property></bean>
</mvc:message-converters>
</mvc:annotation-driven>
还需在对应日期属性加上@JsonFormat标签.