Json对象通过Android RetroFit进入数组列表

问题描述 投票:0回答:1

我正在尝试从其他API获取此数据并在Recycler视图上显示。我尝试将JSON对象转换为ArrayList,但没有成功。我的代码返回了这个:[]目前,我正在对POJO类使用Retrofit。

My JSON

//Header

ArrayList<Model> carsModels=new ArrayList<>();
private Adapter carsAdapter;


Retrofit retrofit=new Retrofit.Builder()
            .baseUrl("http://example.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInteface requestInteface = retrofit.create(RequestInteface.class);
    Call<Model> call = requestInteface.getInteressJson();

    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {
            if(response.isSuccessful()){
                carsModels = new ArrayList<>(response.body().getModelList()); 
                carsAdapter = new Adapter(home.this, carsModels);
                cars_recyclerview.setAdapter(carsAdapter);
                Toast.makeText(home.this,"Success",Toast.LENGTH_SHORT).show();
            }
        }

    });

模型类别:

public class Model {
@SerializedName("name")
@Expose
private String name;
@SerializedName("audience_size")
@Expose
private String audience_size;
@SerializedName("topic")
@Expose
private String topic;
@SerializedName("path")
@Expose
private String path;
@SerializedName("description")
@Expose
private String description;

private List<Model> modelList = new ArrayList<>();


//Getter and setter

请求接口:

interface RequestInteface {
@GET("search.json")
Call<Model> getInteressJson();
}
android json api retrofit
1个回答
0
投票

您首先需要解析“数据”,在“数据”内部包含List<Model>创建类InteressResponse

public class InteressResponse {
@SerializedName("name")
@Expose
private List<Model> modelList;

//Getter and setter
}
interface RequestInteface {
@GET("search.json")
Call<InteressResponse> getInteressJson();
}
public void onResponse(Call<InteressResponse> call, Response<InteressResponse> response) {
      if(response.isSuccessful()){
          carsModels = new ArrayList<>(response.body().getModelList()); 
          carsAdapter = new Adapter(home.this, carsModels);
          cars_recyclerview.setAdapter(carsAdapter);
          Toast.makeText(home.this,"Success",Toast.LENGTH_SHORT).show();
      }
}

删除类private List<Model> modelList = new ArrayList<>();中的Model

© www.soinside.com 2019 - 2024. All rights reserved.