[英]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.