有没有办法使翻新/ gson的时间戳加倍?

时间:2019-04-16 20:22:23

标签: java json casting gson retrofit2

我正在开发Android应用。我正在对Gson进行改造,以调用服务器并进行序列化/反序列化。在请求中,有一个包含timestamplong)的响应类。有时它是double,因为该应用程序的iOS版本使用double来存储时间戳。

是否有一种方法可以强制Gson反序列化响应并将其强制转换为Response类(长)上存在的对象?

例外:

Caused by com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Expected a long but was 1555323142345.364 at line 1 column 1002 path $.userSettings.stories[4].readTimestamp
       at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:323)
       at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:313)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
       at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
       at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
       at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
       at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
       at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
       at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
       at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:119)
       at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:218)
       at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
       at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
       at inesc_id.pt.motivandroid.motviAPIClient.MotivAPIClientManager$CheckOnboardingNeededAndRetrieve.doInBackground(MotivAPIClientManager.java:909)
       at inesc_id.pt.motivandroid.motviAPIClient.MotivAPIClientManager$CheckOnboardingNeededAndRetrieve.doInBackground(MotivAPIClientManager.java:711)
       at android.os.AsyncTask$2.call(AsyncTask.java:307)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run(Thread.java:833)

班级:



public class StoryStateful implements Serializable{

    @Expose
    int storyID;

    @Expose
    boolean read;

    @Expose
    long readTimestamp;

    @Expose
    long availableTimestamp;
}


1 个答案:

答案 0 :(得分:1)

For simplicity assume that your JSON payload is:

{
    "timestamp": 1555323142345.345
}

And it should fit to:

class Pojo {

    private long timestamp;

    // getters, setters, toString
}

Solution depends whether you can change Pojo model or not. In case yes and you want to store double and long it is possible to change type to Number:

private Number timestamp;

And you should be able to parse double's and long's timestamps. In case you always want to have long you need to implement custom deserialiser:

class LongOrDoubleJsonDeserializer implements JsonDeserializer<Long> {

    @Override
    public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonPrimitive()) {
            Number number = json.getAsNumber();

            return number.longValue();
        }

        return null;
    }
}

And your Pojo property should look like:

@JsonAdapter(LongOrDoubleJsonDeserializer.class)
private long timestamp;

If you can not change Pojo class you need to implement custom TypeAdapterFactory and register using GsonBuilder. See this link: Creating the Retrofit instance. Custom implementation could look like:

class LongOrDoubleTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Class<? super T> rawType = type.getRawType();
        if (rawType == Long.class || rawType == long.class) {
            return new TypeAdapter<T>() {
                @Override
                public void write(JsonWriter out, T value) {
                }

                @Override
                public T read(JsonReader in) throws IOException {
                    try {
                        return (T) new Long(in.nextLong());
                    } catch (NumberFormatException e) {
                        return (T) new Long(((Double) in.nextDouble()).longValue());
                    }
                }
            };
        }
        return null;
    }
}

And register as below:

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(new LongOrDoubleTypeAdapterFactory())
    .create();