Json格式日期转换问题

一.@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

  1. 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标签.
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值