如何在RetroFit中使用Gson转换器?

vic*_*ele 23 java android gson retrofit

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

我已经正确地导入了Retrofit库(至少我认为我有)但是我无法获得Gson Converter包.我安装了谷歌的gson.jar但是在这些库中没有任何一个地方有一个名为"GsonConverterFactory"的类,这是我解析JSON所必需的.

编辑:我在Windows上.

man*_*noj 22

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

所以我的建议是使用 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'
Run Code Online (Sandbox Code Playgroud)


iag*_*een 19

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

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


Joo*_*lah 14

试试这个

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


far*_*ruk 13

在您的模块中:app build.gradle add

compile 'com.squareup.retrofit2:converter-gson:[retrofit2 version]'
Run Code Online (Sandbox Code Playgroud)

上面的版本与你的retrofit2版本相同,例如你的retrofit2版本是2.1.0,而你的build.gradle应该是这样的:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Run Code Online (Sandbox Code Playgroud)