【问题标题】:How do I use the Gson converter in RetroFit?如何在 RetroFit 中使用 Gson 转换器?
【发布时间】:2015-12-02 09:46:55
【问题描述】:

我正在为教育目的制作一个简单的 RetroFit 应用程序,并使用 IntelliJ IDEA 作为我的 IDE。

我已经正确导入了 Retrofit 库(至少我认为我已经导入了),但我无法获得 Gson Converter 包。我安装了来自 google 的 gson.jar,但在这两个库中都没有一个名为“GsonConverterFactory”的类,这是我解析 JSON 所必需的。

编辑:我在 Windows 上。

【问题讨论】:

    标签: java android gson retrofit


    【解决方案1】:

    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' 添加到您的build.gradle 文件并解决依赖关系或将相应的jar 添加到您的bulid 路径。

    然后使用GsonConverterFactory.create() 获取Converter Factory

    我尝试使用2.0.0-beta1,但它给了我一个非法的工厂类型转换错误,如下所示,所以移到2.0.0-beta2

      error: method addConverterFactory in class Builder cannot be applied to   given types;
        required: Factory
        found: GsonConverterFactory
        reason: actual argument GsonConverterFactory cannot be converted to Factory by method invocation conversion
    

    所以我的建议是使用2.0.0-beta2

    我的 build.gradle 具有以下依赖项来解决改造问题。

     compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'  
     compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    

    【讨论】:

    • iagreen 的回答不适用于改造 beta2。如果使用改造 2,我们需要使用转换器-gson beta 2,如 @manoj 所说。
    • 收到错误 - 无法解决 - 对于上述这些依赖项
    【解决方案2】:

    如果您使用改造 2,则需要包含 convert-gson 包。对于 gradle 构建,您可以将 compile 'com.squareup.retrofit:converter-gson:2.0.0-beta3' 添加到您的依赖项部分。

    对于其他构建系统,或下载 jar,请查看 Maven Central convert-gson 页面。

    【讨论】:

      【解决方案3】:

      试试这个

      /* JSON */
      compile 'com.google.code.gson:gson:2.5'
      compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
      
      // >Retrofit & OkHttp
      compile ('com.squareup.retrofit2:retrofit:2.0.0-beta3') {
          // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
          exclude module: 'okhttp'
      }
      compile 'com.squareup.okhttp3:okhttp:3.0.1'
      

      【讨论】:

        【解决方案4】:

        在您的模块中:app build.gradle 添加

        compile 'com.squareup.retrofit2:converter-gson:[retrofit2 version]'
        

        上面的版本和你的retrofit2版本是一样的,比如你的retrofit2版本是2.1.0,那么你的build.gradle应该是这样的:

        compile 'com.squareup.retrofit2:retrofit:2.1.0'
        compile 'com.squareup.retrofit2:converter-gson:2.1.0'
        

        【讨论】:

        • 这对我有用 - 指定它们必须完全相同
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 2018-02-10
        • 2017-06-11
        • 2014-12-28
        • 2017-10-30
        • 2019-03-24
        • 1970-01-01
        相关资源
        最近更新 更多