2 回答

TA贡献1852条经验 获得超1个赞
使用 Gson 直接解析响应
更新搜索结果
public class SearchResults {
int page;
List<List<SearchItem>> data;
public int getPage() {
return page;
}
public List<List<SearchItem>> getData() {
return data;
}
}
您可以像这样访问 item_type
searchResult.getData.get(i).get(0).item_type

TA贡献1853条经验 获得超18个赞
在您的接口改造函数中使用 Response 作为返回类型,如下所示
@GET("Search")
Observable<Response<ResponseBody>> search(@Query(ParamsHolder.GET_QUERY)
String query, @Query(ParamsHolder.GET_PAGE) int page);
这样您就可以检索完整的 json 正文,并且您现在可以完全控制如何根据 item_type 解析数据
所以基本上你调用函数 response.body().string() 来获取json体
而不是您手动解析,如下所示:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response.body().string());
JSONArray jsonArray = jsonObject.getJSONArray("data");
//looping through the data array
for(int i = 0;i<jsonArray.length();i++){
JSONArray childArr = jsonArray.getJSONArray(i);
//looping through current child array inside data
for(int j = 0;j<childArr .length();j++){
JSONObject nestedChildObj =childArr.getJSONObject(j);
//now i have access to item_type
int item_type = nestedChildObj .getInt("item_type")
//now you can use gson to parse the nestedChildObj based
//on item_type or manually do the parsing
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
添加回答
举报