我是新的Android应用程序开发与java和我试图从外部API获取数据。然而,我得到的错误:Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
。API会以下列格式传回结果:
[ {} ,{} , ... ]
其中我将每个对象定义为一个结果,并在API接口中列出这些结果。
每个对象的形式为:
{
area: "athens",
areaid: 1002,
dailydose1: 276,
dailydose2: 305,
daydiff: -49,
daytotal: 581,
referencedate: "2021-05-27T00:00:00",
totaldistinctpersons: 25446,
totaldose1: 25446,
totaldose2: 12098,
totalvaccinations: 36960
}
我的代码:
CovidApi.java
public interface CovidApi {
@GET("/")
Call<List<CovidSingleResult>> getCovidData();
}
CovidSingleResult.java
public class CovidSingleResult {
private int totalvaccinations;
private int daytotal;
private String referencedate;
private int totaldose1;
private int totaldose2;
private String area;
private int areaid;
private int dailydose1;
private int dailydose2;
private int daydiff;
public String getArea() {
return area;
}
public int getDailydose1() {
return dailydose1;
}
public int getDaytotal() {
return daytotal;
}
public int getDailydose2() {
return dailydose2;
}
public String getReferencedate() {
return referencedate;
}
public int getAreaid() {
return areaid;
}
public int getTotaldose1() {
return totaldose1;
}
public int getTotaldose2() {
return totaldose2;
}
public int getDaydiff() {
return daydiff;
}
public int getTotalvaccinations() {
return totalvaccinations;
}
}
Fragment.java ,我在这里调用api url
resultText = root.findViewById(R.id.response); //text to set api result
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://data.gov.gr/api/v1/query/mdg_emvolio/date_from="+binding.inputFrom.getText()+"&date_to="+binding.inputTo.getText()+"/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
CovidApi covidApi = retrofit.create(CovidApi.class);
Call<List<CovidSingleResult>> call = covidApi.getCovidData();
call.enqueue(new Callback<List<CovidSingleResult>>() {
@Override
public void onResponse(Call<List<CovidSingleResult>> call, retrofit2.Response<List<CovidSingleResult>> response) {
if(!response.isSuccessful()){
resultText.setText("Code" + response.code());
return;
}else{
List<CovidSingleResult> covidSingleResults = response.body();
for(CovidSingleResult p : covidSingleResults){
String content = "";
content += "total vaccinations :" + p.getTotalvaccinations();
resultText.append(content);
}
}
}
@Override
public void onFailure(Call<List<CovidSingleResult>> call, Throwable t) {
resultText.setText(t.getMessage());
}
});
我会很感激你的帮助
1条答案
按热度按时间aurhwmvo1#
错误说您的响应是对象,而您的java模型是列表,请替换api接口中的以下代码: