我知道如何接收这种类型的数组:
[
{
"username": "luis",
"job": "developer",
"age": 23
}
]
我的问题是当我必须接收一个具有特定名称的数组时,如下所示:
{"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"}]}
在这种情况下,我必须使用retrofit2 接收上面名为“result”的数组。任何人都可以帮助我我是 Retrofit 的新手。
这是我尝试过的:
主要活动
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Workers>> call = apiInterface.getWorkers();
call.enqueue(new Callback<List<Workers>>() {
@Override
public void onResponse(Call<List<Workers>> call, Response<List<Workers>> response) {
list=response.body();
adapter = new WorkerAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
}
@Override
public void onFailure(Call<List<Workers>> call, Throwable t) {
}
});
Api客户端:
public class ApiClient {
public static final String BASE_URL="http://192.168.31.206/test1_database/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient(){
if (retrofit==null){
retrofit=new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
接口:
public interface ApiInterface {
@GET("getAllUser.php")
Call<List<Workers>> getWorkers();
}
我的 POJO 或 Workers 类:
public class Workers {
@SerializedName("username")
String Name;
@SerializedName("job")
String Job;
@SerializedName("age")
int Age;
public String getName() {
return Name;
}
public String getJob() {
return Job;
}
public int getAge() {
return Age;
}
}
最后是我的 RecyclerAdpter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
Context context;
List<Workers> list;
public WorkerAdapter(Context context,List<Workers> list) {
this.context = context;
this.list = list;
}
我已经被困了两天了,我仍然无法解决它。请帮忙!
慕桂英4014372
桃花长相依
慕少森
相关分类