spring处理数据库中Date类型字段转换成时间戳问题
有两种⽅式可以解决⽇期转换Json问题:
1、(不推荐)局部修改,⾃定义注解进⾏将⽇期类型转换为Date类型。
2、(强烈推荐)全局修改,⽤MappingJackson2HttpMessageConverter配置在XML(SpringMVC)或者配置在Application.Java启动类(Spring boot、Spring cloud)。
配置在Application.Java启动类(Spring boot、Spring cloud):
@Bean
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
//设置⽇期格式
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
objectMapper.setDateFormat(smt);
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
//设置中⽂编码格式
List<MediaType> list = new ArrayList<MediaType>();
java时间日期格式转换list.add(MediaType.APPLICATION_JSON_UTF8);
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
return mappingJackson2HttpMessageConverter;
}
配置在XML(SpringMVC):
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.verter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="customObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
⾃定义objectMapper:
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
CustomSerializerFactory factory = new CustomSerializerFactory();
factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
@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);
}
}
注意:如果想要单个bean的某个⽇期字段显⽰年⽉⽇时分秒的话,只需要在对应⽇期的get⽅法上添加@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")即可。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论