spring-mvc版本4.2.5
jackson-databind 2.7.4
自定义JsonSerializer处理类、这里用java.sql.Timestamp类型转换
public class TimestampSerializer extends JsonSerializer<Timestamp> {
@Override
public void serialize(Timestamp timestamp, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(Tools.date2Str(timestamp, "yyyy-MM-dd HH:mm:ss"));
}
}
自定义ObjectMapper、ObjectMapper类com.fasterxml.jackson.databind.ObjectMapper
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
SimpleModule module = new SimpleModule();
module.addSerializer(Timestamp.class, new TimestampSerializer());
this.registerModule(module);
}
}
在xml中配置自定义的ObjectMapper类、把该类配置到MappingJackson2HttpMessageConverter中
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="objectMapper">
<bean class="*.*.CustomObjectMapper">
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
配置完成后返回的Timestamp类型就会自动转换为yyyy-MM-dd HH:mm:ss格式