改造:gson stackoverflow

0 java android gson retrofit

我尝试使用Retrofit和gson库发出API请求,我按照本教程通过改造来制作我的API请求:http: //blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/但是我遇到错误.这是日志消息的不同部分:

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)
Run Code Online (Sandbox Code Playgroud)

这是类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();
}
}
Run Code Online (Sandbox Code Playgroud)

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我提出了一个请求,一切正常,我得到了正确的答案,我可以得到值,但在请求后出现这个错误,我不明白为什么,这是Gson库的问题吗?有办法解决这个问题吗?

我试试Nexus 5 android 5.0.1,改进1.9.0和gson 2.3.1

预先感谢您的任何帮助 !

Tus*_*gna 5

当Gson尝试解析有关必须反序列化的对象的类型信息时,会发生错误.由于在extends声明中对Book类的循环引用,它会进入无限递归.

然而即使Gson可以应付你的课程,我也不建议使用这些库组合.遇到兼容性问题时会发生这种情况.尝试使用版本的Gson并从项目中删除改进依赖项.

希望能帮助到你!