[英]How to handle dynamic JSON with Retrofit 2?
我对一个网址有2种响应。 第一个是对象列表,第二个是错误响应对象。
第一:
[
{
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());
}
});
}
我看到的是您的服务器在HTTP_STATUS 200上发送错误。这就是为什么改造将其视为响应而不是错误。 在服务器端进行此更改将导致公共无效onFailure(Call>调用,Throwable t)调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.