我真的很慢,我无法掌握如何初始化要进入对象然后进入数组的方法。
我尝试过使用Components制作新的Gson,但我不知道如何做。
我是否应该在模型中创建一个新的类,那就是一个数组?然后执行<ArrayList<Component.Components(inside class)>>
吗?
型号
public class Component {
@SerializedName("total")
transient private Integer total;
@SerializedName("rows")
private ArrayList<Rows> rows;
public class Rows {
@SerializedName("name")
private String name;
@SerializedName("image")
private String image;
@SerializedName("serial")
private String serial;
@SerializedName("purchase_cost")
private String cost;
public Rows(String name, String image, String serial, String cost) {
this.name = name;
this.image = image;
this.serial = serial;
this.cost = cost;
}
//getters
}
}
API
@GET("api/v1/components")
Call<ArrayList<Component.Rows>> listComponents();
MainActivity
JsonPlaceHolderApi jsonPlaceHolderApi = ApiClient.getClient().create(JsonPlaceHolderApi.class);
Call<ArrayList<Component.Rows>> call = jsonPlaceHolderApi.listComponents();
call.enqueue(new Callback<ArrayList<Component.Rows>>() {
@Override
public void onResponse(@NonNull Call<ArrayList<Component.Rows>> call, @NonNull Response<ArrayList<Component.Rows>> response) {
ArrayList<Component.Rows> posts = response.body();
componentAdapter = new ComponentAdapter(getApplicationContext(),posts);
listView.setAdapter(componentAdapter);
}
JSON:
{
"total": 1,
"rows": [
{
"id": 1,
"name": "HP ENVY x360 - 13-ag0017nn - 4UE32EA AMD® Raven Ridge Ryzen 7 2700U do 3.8GHz, 13.3", 512GB SSD, 8GB",
"image": "http://server/uploads/components/7cDXBttwk2O5p5sEM5T9raBvW.png",
"serial": "193015227095",
"location": {
"id": 1,
"name": "ICB"
},
这是响应json。
答案 0 :(得分:0)
我不熟悉您的代码,但希望我的回答对您有帮助。.您可以通过将Arrays类用作
从数组中获取ArrayListArrays.asList(myArray);
它返回myArray中的项目列表,还接受var参数 您可以在一行中使用它,例如
List<Integer> l = new ArrayList<>(asList(5,4,4,4));
或
Integer[]arr = new Integer[5];
List<Integer> l = new ArrayList<>(asList(arr));
答案 1 :(得分:0)
根据您的响应json
{
"total": 1,
"rows": [
{
"id": 1,
"name": "HP ENVY x360.....",
"image": "http://server/uploads/components/7cDXBttwk2O5p5sEM5T9raBvW.png",
"serial": "193015227095",
"location": {
"id": 1,
"name": "ICB"
}
},
.. similar objects ...
]
}
您收到的班级结构应类似于
class ResponseData {
private int total;
private List<RowData> rows;
// todo: getters & setters
public class RowData {
private int id;
private String name;
// etc etc
private LocationData location;
public class LocationData {
private int id;
private String name;
// etc etc
}
}
}
然后,您的API和活动变为
// API
Call<ResponseData> listComponents();
// activity code
Call<ResponseData> call = jsonPlaceHolderApi.listComponents();
// reading rows
ResponseData response = response.body();
response.getRows();
希望您能理解。