全局配置
spring-mvc.xml配置
在< mvc:annotation-driven />之前配置
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<!-- 设置全局返回JSON到前端时日期格式化 -->
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</list>
</property>
</bean>
<!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射 -->
<mvc:annotation-driven />
controller
@RequestMapping("json")
@ResponseBody
public List<Person> listp(HttpServletRequest request) {
return personService.getAll();
}
配置之前
[
{
id: 1,
username: "1",
address: "1",
phone: "1",
remark: "1",
mony: 1000,
birthday: 1520265600000
},
{
id: 2,
username: "tom",
address: null,
phone: "123",
remark: "mark",
mony: 19000,
birthday: 1520301623000
}
]
配置之后
[
{
id: 1,
username: "1",
address: "1",
phone: "1",
remark: "1",
mony: 1000,
birthday: "2018-03-06 00:00:00"
},
{
id: 2,
username: "tom",
address: null,
phone: "123",
remark: "mark",
mony: 19000,
birthday: "2018-03-06 10:00:23"
}
]
局部配置
public class YmdDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(value);
jgen.writeString(formattedDate);
}
}
在需要你特殊转化的地方
@JsonSerialize(using=YmdDateSerializer.class)
private Date birthDay;