使用Retrofit库来使用服务,我已经为我的界面,模型以及我如何使用界面添加了代码。
我一直在扔GSON“预计BEGIN_OBJECT但是BEGIN_ARRAY”
接口
@GET("api/RetrofitAndroidArrayResponse")
Call<student> getStudentDetails();
模型 公立班学生{
//Variables that are in our json
private int StudentId;
private String StudentName;
private int StudentMarks;
//Getters and setters
public int getStudentId() {
return StudentId;
}
public void setStudentId(int bookId) {
this.StudentId = StudentId;
}
public String getStudentName() {
return StudentName;
}
public void setStudentName(String name) {
this.StudentName = StudentName;
}
public int getStudentMarks() {
return StudentMarks;
}
public void setStudentMarks(String price) {
this.StudentMarks = StudentMarks;
}
}
我如何调用方法
void getRetrofitObject() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
object service = retrofit.create(object.class);
Call<student> call = service.getStudentDetails();
call.enqueue(new Callback<student>() {
@Override
public void onResponse(Response<student> response, Retrofit retrofit) {
try {
text_id_1.setText("StudentId : " + response.body().getStudentId());
text_name_1.setText("StudentName : " + response.body().getStudentName());
text_marks_1.setText("StudentMarks : " + response.body().getStudentMarks());
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
}
答案 0 :(得分:1)
您收到的响应是Array格式,但您将模型作为Student对象。 请提供您收到的JSON回复。 使用HttpLoggingInterceptor记录响应。
答案 1 :(得分:0)
感谢您的帮助
这是一个愚蠢的错误。调用期望一个对象,并指向返回对象列表的url。
我刚刚更改了网址并且找到了
@GET("api/RetrofitAndroidObjectResponse")
Call<Student> getStudentDetails();