我在JSONbin.io中有一些具有以下结构的JSON对象:
{
"employee_contributions": [
{
"transaction_id": "01",
"staff_no": "12",
"ammount": "10000",
"date": "20-2-2020"
}
],
"employer_contributions": [
{
"transaction_id": "01",
"staff_no": "12",
"ammount": "10000",
"date": "20-2-2020"
}
]
}
我想访问employee_contributions数组中的对象,但是出现404错误。我相信我的网址是问题,但我不知道为什么。这是相关的主要活动代码:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.jsonbin.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
yeeAPI yeeapi = retrofit.create(yeeAPI.class);
Call<List<yee_contributions>> call = yeeapi.getYee_Contributions();
call.enqueue(new Callback<List<yee_contributions>>() {
@Override
public void onResponse(Call<List<yee_contributions>> call, Response<List<yee_contributions>> response) {
if (!response.isSuccessful()) {
yee_contr.setText("code: " + response.code());
return;
}
List<yee_contributions> contrs = response.body();
for (yee_contributions yee_contributions : contrs){
String content = "";
content+=yee_contributions.getTransaction_id()+" ";
content+=yee_contributions.getStaff_no()+" ";
content+=yee_contributions.getAmmount()+" ";
content+=yee_contributions.getDate()+"\n\n";
yee_contr.append(content);
}
}
@Override
public void onFailure(Call<List<yee_contributions>> call, Throwable t) {
yee_contr.setText(t.getMessage());
}
});
这是我的界面:
public interface yeeAPI {
@GET("b/5e536928d3c2f35597f6ca46/3/employeee_contributions")
Call<List<yee_contributions>> getYee_Contributions();
}
我的模型课程:
public class yee_contributions {
private String transaction_id;
private String staff_no;
private String ammount;
private String date;
public String getTransaction_id() {
return transaction_id;
}
public String getStaff_no() {
return staff_no;
}
public String getAmmount() {
return ammount;
}
public String getDate() {
return date;
}
}
基本URL很好。只有当我将/employee_contributions
添加到端点时,我才会收到404错误。
答案 0 :(得分:1)
您不能以这种方式访问employeee_contributions
。您必须先获取全部数据,然后从中解析employeee_contributions
。为此,您必须进行一些更改。检查以下内容:
步骤-1::要使您的json
响应与其他模型保持一致,如下所示:
public class YeeResponse {
private List<yee_contributions> employee_contributions;
private List<yee_contributions> employer_contributions;
//getter-setter
}
步骤-2:更改您的API接口,使其如下所示:
public interface yeeAPI {
@GET("b/5e536928d3c2f35597f6ca46/3/")
Call<YeeResponse> getYee_Contributions();
}
步骤-3:更改enqueue
的实现并解析数据,如下所示:
Call<YeeResponse> call = yeeapi.getYee_Contributions();
call.enqueue(new Callback<YeeResponse>() {
@Override
public void onResponse(Call<YeeResponse> call, Response<YeeResponse> response) {
if (!response.isSuccessful()) {
return;
}
YeeResponse yeeResponse = response.body();
List<yee_contributions> employee_contributions = yeeResponse.getEmployee_contributions();
// Now loop through employee_contributions to get yee_contributions
....
}
@Override
public void onFailure(Call<YeeResponse> call, Throwable t) {
....
}
});