如何转换Jackson和Gson之间的日期?

Gob*_*ber 5 java json timestamp jackson gson

在我们的Spring配置的REST服务器中,我们使用Jackson将对象转换为Json.该对象包含几个java.util.Date对象.

当我们尝试使用Gson的fromJson方法在Android设备上反序列化时,我们得到一个"java.text.ParseException:Unparseable date".我们尝试将日期序列化为自1970年以来相应于毫秒的时间戳,但得到相同的异常.

可以将Gson配置为将时间戳格式的日期(例如1291158000000)解析为java.util.Date对象吗?

dog*_*ane 6

您需要为日期注册自己的反序列化程序.

我在下面创建了一个小例子,其中JSON字符串"23-11-2010 10:00:00"被反序列化为Date对象:

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;


public class Dummy {
    private Date date;

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {

                SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                String date = json.getAsJsonPrimitive().getAsString();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Gson gson = builder.create();
        String s = "{\"date\":\"23-11-2010 10:00:00\"}";
        Dummy d = gson.fromJson(s, Dummy.class);
        System.out.println(d.getDate());
    }
}
Run Code Online (Sandbox Code Playgroud)