Retrofit 2示例教程但GsonConverterFactory显示错误"无法解析符号"

Sta*_*wer 31 android gson android-library retrofit okhttp

我正在尝试遵循Retrofit的2 教程,但是在这部分代码中有一个GsonConverterFactory显示错误Cannot resolve symbol:

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://your.api-base.url";

    private static OkHttpClient httpClient = new OkHttpClient();
    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    //THIS IS THE LINE WITH ERROR!!!!!!!!!!!!
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient).build();
        return retrofit.create(serviceClass);
    }
}
Run Code Online (Sandbox Code Playgroud)

之前我在gradle.build中添加了,我不确定是否应该添加GSON,因为他们说Retrofit 1.9有它但是没有提到Retrofit 2:

dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
}
Run Code Online (Sandbox Code Playgroud)

Bla*_*elt 77

编辑

改造2现在稳定.使用

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

在您的build.gradle依赖项部分

老答案

使用Retrofit 2.0,您必须在build.gradle中声明要使用的转换工厂.加

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

到你的gradle并再次同步它


And*_*oke 11

来自该网站上的另一篇文章

默认情况下,改装2不随Gson一起提供.以前,你不需要担心任何集成的转换器,你可以开箱即用Gson.此库更改会影响您的应用程序,您还需要将转换器导入为兄弟包.我们稍后会在这篇文章中触摸转换器,并向您展示如何为您的应用配置Gson或任何其他响应转换器.

因此,将此添加到您的 build.gradle

dependencies {  
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
}
Run Code Online (Sandbox Code Playgroud)


小智 5

新版本现已推出

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