无法为 java.util.List Retrofit 2.0.0-beta2 创建转换器

2022-09-03 04:05:29

我只是在做一个GET请求,但我得到这个错误:

java.lang.RuntimeException:无法启动 Activity ComponentInfo{com.example.yomac_000.chargingpoint/com.example.yomac_000.chargingpoint.AllStores}: java.lang.IllegalArgumentException: Unable to create converter for java.util.List

这是因为这行代码:

Call<List<Store>> call = subpriseAPI.listStores(response);

所以我尝试了这行代码,看看它是什么类型:

System.out.println(subpriseAPI.listStores(response).getClass().toString());

但后来我得到了同样的错误,所以它不会让我知道它是什么类型。在下面,您可以看到我的代码。

商店服务.java:

public class StoreService {

    public static final String BASE_URL = "http://getairport.com/subprise/";
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .build();

    SubpriseAPI subpriseAPI = retrofit.create(SubpriseAPI.class);
    String response = "";

    public List<Store> getSubprises() {

        Call<List<Store>> call = subpriseAPI.listStores(response);

        try {
            List<Store> listStores = call.execute().body();

            System.out.println("liststore "+ listStores.iterator().next());
            return listStores;
        } catch (IOException e) {
            // handle errors
        }
        return null;
    }
}

SubpriseAPI.java:

public interface SubpriseAPI {
    @GET("api/locations/get")
    Call<List<Store>> listStores(@Path("store") String store);
}

商店.java:

public class Store {
    String name;
}

我使用的是改造版本2.0.0-beta2。


答案 1

在2 +版本中,您需要通知转换器

变换 器

默认情况下,Retrofit只能将HTTP主体反序列化为OkHttp的RecertBody类型,并且它只能接受其RequestBody类型@Body。

可以添加转换器以支持其他类型。六个同级模块为方便起见,可改编流行的序列化库。

Gson: com.squareup.retrofit:converter-gson Jackson: com.squareup.retrofit:converter-jackson
Moshi: com.squareup.retrofit:converter-moshi
Protobuf: com.squareup.retrofit:converter-protobuf
Wire: com.squareup.retrofit:converter-wire
Simple XML: com.squareup.retrofit:converter-simplexml

// Square libs, consume Rest API
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

所以

String baseUrl = "" ;
Retrofit client = new Retrofit.Builder()
    .baseUrl(baseUrl)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

答案 2
public interface SubpriseAPI {
     @GET("api/locations/get")
     Call<List<Store>> listStores(@Path("store") String store);
}

您声明了一个被调用的存储,因此在您的注释中,改造期望找到替换的占位符。例如:@Path@GET

@GET("api/locations/{store}")
Call<List<Store>> listStores(@Path("store") String store);

推荐