Is there a way to make retrofit/gson cast a double timestamp to long?

Poider12 :

I'm developing an Android app. I'm using retrofit with Gson to make calls to the server and serialize/deserialize. In a request, there is a response class which contains a timestamp (long). Sometimes it is a double since the iOS version of the app uses double to store timestamps.

Is there a way to force Gson to deserialize the response and cast to the object present on the Response class(long)?

Exception:

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)

Class:



public class StoryStateful implements Serializable{

    @Expose
    int storyID;

    @Expose
    boolean read;

    @Expose
    long readTimestamp;

    @Expose
    long availableTimestamp;
}


Michał Ziober :

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134416&siteId=1