返回Json时格式化日期Date第一步:创建CustomObjectMapper类
/**
* 解决SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳的问题。需配合使用
*/
@Component("customObjectMapper")
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
CustomSerializerFactory factory = new CustomSerializerFactory();
factory.addGenericMapping(Date.class, new JsonSerializer() {
@Override
public void serialize(Date value, JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
});
this.setSerializerFactory(factory);
}
}
第二步:配置如下:
效果如下:
格式化前
格式化后
进阶:返回自定义格式日期使用@ResponseBody时返回json字符串的日期格式。Date类型属性默认返回一个Long型的时间戳,怎样能够返回自定义的日期格式?
解决方案:目前有两种方式实现,
1、局部修改(网上较多,但不推荐);继承Jackson的抽象类:JsonSerializer,然后在javabean的属性getter()上添加注解@JsonSerialize即可实现。
代码如下:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
/**
* @description 自定义返回JSON 数据格中日期格式化处理
*/
public class CustomDateSerializer extends JsonSerializer {
@Override
public void serialize(Date value,
JsonGenerator jsonGenerator,
SerializerProvider provider)
throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
}
使用方式:
@JsonSerialize(using = CustomDateSerializer.class)
public Date getCreateDate() {
return createDate;
}
2、全局修改(强烈推荐):MappingJacksonHttpMessageConverter主要通过ObjectMapper来实现返回json字符串。这里我们继承该类,注册一个JsonSerializer。然后在配置文件中注入自定义的ObjectMapper。
代码如下:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
/**
* @description 解决Date类型返回json格式为自定义格式
*/
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(){
CustomSerializerFactory factory = new CustomSerializerFactory();
factory.addGenericMapping(Date.class, new JsonSerializer(){
@Override
public void serialize(Date value,
JsonGenerator jsonGenerator,
SerializerProvider provider)
throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
});
this.setSerializerFactory(factory);
}
}
spring-servlet.xml中配置: