Gson使用心得(一):Date的处理

首先,先介绍一下Gson。


这是Gson的GitHub主页:https://github.com/google/gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Gson Goals
  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)


简单来说,Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。


关于Gson的文章,网上已经茫茫多了,我就不再赘述。


今天要记录的是关于日期时间的处理。

以下是,通常我们使用Gson的方式。

import java.util.Date;

import com.google.gson.Gson;

public class DateGsonTest {

    private String name;

    private Date now;

    public static void main(String[] args) {
        DateGsonTest dgt = new DateGsonTest();

        dgt.setName("Lance");
        dgt.setNow(new Date());
        
        Gson gson = new Gson();
        String dgtStr = gson.toJson(dgt);
        System.out.println("The json string of dgt:" + dgtStr);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getNow() {
        return now;
    }

    public void setNow(Date now) {
        this.now = now;
    }
}


第19行的打印输出为:The json string of dgt:{"name":"Lance","now":"Dec 29, 2015 4:35:43 PM"}


Date被序列化之后显示日期和时间的格式与locale环境有关。
当这样的Json在不同的locale环境中反序列化之后,几乎必然发生反序列化异常的问题。
所以,在不同的locale环境中,gson的序列化和反序列化必须明确约定日期时间格式。


具体做法如下:

package com.kxtech.goonie.common.util;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;


public class UtilDateGSON implements JsonSerializer, JsonDeserializer {

    private static final Log logger = LogFactory.getLog(UtilDateGSON.class);

    @Override
    public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new JsonPrimitive(sdf.format(arg0));
    }

    @Override
    public Date deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(arg0.getAsJsonPrimitive().getAsString());
        } catch (ParseException e) {
            logger.error("UtilDateGSON deserialize error.", e);
        }

        return date;
    }

}

编写自己的UtilDateGSON类,实现JsonSerializer和Deserializer两个接口中的两个方法。这样就明确约定了日期时间格式。

此时,gson对象不能再以new的方式创建实例,必须使用GsonBuilder类注册类型适配器并create gson对象。

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtilDateGSON()).create();

此时,第十九行的打印输出为:The json string of dgt:{"name":"Lance","now":"2015-12-29 17:05:36"}

OK,此坑已填。


最后,通常为我们会用Spring 来管理Bean,gson在spring的xml中可以通过factory-method的方式创建实例


package com.kxtech.goonie.common.util;

import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MyGsonFactory {

    public static Gson buildGson() {
        return new GsonBuilder().registerTypeAdapter(Date.class, new UtilDateGSON()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    }

}

<bean id="gson" class="com.kxtech.goonie.common.util.MyGsonFactory" factory-method="buildGson" />



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值