简体   繁体   中英

GSON deserialized for type of Timestamp

I want to deserialize timestamp by using gson in java.

// 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}

However, I got this exception.

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)

How can I deserialize timestamp for long such as 1546476882?

As @johnheroy already commented, you need a TypeAdapter for adapting between Timestamp objects and long values (apparently you have seconds since 1970-01-01, the Unix epoch).

This adapter would be very simple

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
    }
}

You need to register this adapter with Gson like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM