简体   繁体   中英

Retrofit : gson stackoverflow

I try to make API requests with Retrofit and gson library , I followed this tutorial to make my API request with retrofit : http://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/ but I encounter an error. This is different parts of log message :

Retrofit﹕ java.lang.StackOverflowError at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:372)
...

 API.ItemTypeAdapterFactory.create(ItemTypeAdapterFactory.java:20)
        at com.google.gson.Gson.getAdapter(Gson.java:359)

This is the class ItemTypeAdapterFactory:

public class ItemTypeAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>() {

        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {
            JsonElement jsonElement = elementAdapter.read(in);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has("content") && jsonObject.get("content").isJsonObject())
                {
                    jsonElement = jsonObject.get("content");
                }
            }
            return delegate.fromJsonTree(jsonElement);
        }
    }.nullSafe();
}
}

JSON

{
    "http_code":200,
    "content":{
        "token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "expires":"2015-03-18T04:45:53.066Z",
        "client":"XXXXXXXXXXXXXXXXXXXX",
        "createdAt":"2015-02-16T04:45:53.066Z",
        "updatedAt":"2015-02-16T04:45:53.066Z",
        "id":"XXXXXXXXXXXXXXXXXXXXX"
    }
}

So I made a request, everything is ok, I get the right answer and I can get values but after the request this bug appear and I have no idea why, is it an issue from Gson library ? There is a way to fix that ?

I try it on Nexus 5 android 5.0.1, retrofit 1.9.0 and gson 2.3.1

Thank you in advance for any help !

Error happens when Gson tries to resolve type information about an object it have to deserialize. It gets into an infinite recursion due to the cyclic reference to your Book class in extends declaration.

However even if Gson could cope with your class, I would not recommend using these libraries combination. This happens when there are compatibility issues. Try using older version of Gson and remove retrofit dependency from the project.

Hope it helps!

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