GSON反序列化为时间戳类型

时间:2019-01-03 01:10:54

标签: java serialization gson

我想通过在Java中使用gson反序列化时间戳。

// simple class what I want to serialize and deserialize 
public class TestTime {

    private Timestamp time;

}

// and I create gson and try to deserialize it
String body = request.getReader().lines().collect(Collectors.joining());        
TestTime data = gson.fromJson(body, TestTime .class);

// my test data in response body 
{"time": 1546476882}

但是,我遇到了这个例外。

com.google.gson.JsonSyntaxException: 1546476882
    at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:107)
    at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:82)
    at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:35)
    at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)

如何长时间反序列化时间戳(例如1546476882)?

1 个答案:

答案 0 :(得分:0)

正如@johnheroy所评论的那样,您需要TypeAdapter来进行调整 在Timestamp对象和long值之间(显然,自1970年1月1日,Unix时代以来,您有几秒钟)。

此适配器非常简单

public class TimestampAdapter extends TypeAdapter<Timestamp> {

    @Override
    public Timestamp read(JsonReader in) throws IOException {
        return new Timestamp(in.nextLong() * 1000);  // convert seconds to milliseconds
    }

    @Override
    public void write(JsonWriter out, Timestamp timestamp) throws IOException {
        out.value(timestamp.getTime() / 1000);  // convert milliseconds to seconds
    }
}

您需要像这样向Gson注册此适配器:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Timestamp.class, new TimestampAdapter())
        .create();