我对一个网址有两种类型的响应。第一个是对象列表,第二个是错误响应对象。
首先:
[
{
id: 1,
title: "title1",
description: "",
position: 1000
},
{
id: 2,
title: "title3",
description: "",
position: 1000
},
{
id: 3,
title: "title3",
description: "",
position: 1000
}
]
第二
{
"status":"error",
"error":"no token"
}
有关如何使用Retrofit 2处理它的任何想法?当服务器返回错误响应时,我有错误:“预期BEGIN_ARRAY但在第1行第2行路径$ BEGIN_OBJECT”
Category.class
public class Category{
@SerializedName("id")
@Expose
private Id id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("description")
@Expose
private String description;
@SerializedName("position")
@Expose
private Integer position;
/**
*
* @return
* The id
*/
public Id getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Id id) {
this.id = id;
}
/**
*
* @return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* @param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* @return
* The description
*/
public String getDescription() {
return description;
}
/**
*
* @param description
* The description
*/
public void setDescription(String description) {
this.description = description;
}
/**
*
* @return
* The position
*/
public Integer getPosition() {
return position;
}
/**
*
* @param position
* The position
*/
public void setPosition(Integer position) {
this.position = position;
}
}
请求服务器:
public void loadCategories(final boolean pullToRefresh) {
Call<List<Category>> categoriesCall = mRequestHandler.getCategories(Keys.CATEGORY_CATALOGS);
categoriesCall.enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
if (response.isSuccess()) {
getView().setData(response.body());
}
}
@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
getView().showError(null, pullToRefresh);
Log.e("Error:", t.getMessage());
}
});
}
答案 0 :(得分:0)
我可以看到您的服务器在HTTP_STATUS 200上发送错误。 这就是为什么改造将其视为响应而非错误。 将此更改发送到服务器端将导致 public void onFailure(Call&gt; call,Throwable t)invocation。