【问题标题】:Retrofit : gson stackoverflow改造:gson stackoverflow
【发布时间】:2015-11-30 14:04:19
【问题描述】:

我尝试使用 Retrofit 和 gson 库发出 API 请求,我按照本教程使用 Retrofit 发出 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)

这是 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"
    }
}

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

我在 Nexus 5 android 5.0.1、retrofit 1.9.0 和 gson 2.3.1 上试用

提前感谢您的帮助!

【问题讨论】:

  • 你能发布Json吗
  • Json 很好。 Gson一定有问题。当存在兼容性问题时会发生这种情况。尝试使用this 版本的 Gson。
  • 好的,我下载你的版本,我在尝试构建我的项目时遇到了一些问题,让我解决这个问题,我会在一切顺利时与你联系
  • 好的,如果您需要帮助,请告诉我。
  • 问题是改造有依赖关系并使用 gson 2.3.1,当我尝试编译 gson 1.7.1 时,我构建项目时出现冲突,错误是:com.android.dex.DexException: Multiple dex files define Lcom/google/gson/JsonSerializer;我的依赖项是:编译'com.android.support:support-v4:21.0.0' 编译 'com.google.android.gms:play-services:6.1.71' 编译 'com.squareup.okhttp:okhttp-urlconnection:2.2.0' 编译'com.squareup.okhttp:okhttp:2.2.0' compile 'com.squareup.retrofit:retrofit:1.9.0' compile files('libs/gson-1.7.1.jar') 我应该排除改造的 gson 模块吗?

标签: java android gson retrofit


【解决方案1】:

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

但是,即使 Gson 可以应付您的课程,我也不建议使用这些库组合。当存在兼容性问题时会发生这种情况。尝试使用 older 版本的 Gson 并从项目中删除改造依赖。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2019-04-17
    相关资源
    最近更新 更多