我下面有一些JSON。之前我在JSON响应中只有items
元素,并且使用改进来使用以下代码访问它。哪个工作正常。
但是现在我添加了推荐部分,我已经创建了推荐模型,但是现在如何从响应的推荐/项目部分访问数据?
修改 也许有更好的方法可以返回这些数据。可能有500个项目,但只有20/30个列表,所以我认为拆分而不是复制数据会更好。
JSON
[
{
"recommendation": [
{
"following": true,
"list_id": "29",
"list_name": "list29",
},
{
"following": false,
"list_id": "28",
"list_name": "list28",
}
]
},
{
"items": [
{
"description": [
"line1",
"line2",
"line3"
],
"image1": "4367218/img1.jpg",
"item_id": 5600,
"title": "Title 1",
"recommendation_id": 29
},
{
"description": [
"line1",
"line2",
"line3"
],
"image1": "342345/img1.jpg",
"item_id": 3600,
"title": "Tite2",
"recommendation_id": 28
}
]
}
]
推荐模型
public class Recommendation {
private Boolean following;
private int listId;
private String listName;
public Boolean getFollowing() {
return following;
}
// more getters and setters
}
项目模型
public class Item {
private int item_id;
private String title;
private ArrayList<String> description;
private String image1;
private int recommendation_id;
// more getters and setters
}
改进GET
// feed
@GET("/items/{user_id}/{num_items}")
public void getFeedData(@Path("user_id") int user_id, @Path("num_items") Integer num_items, Callback<List<Item>> response);
答案 0 :(得分:1)
{
"recommendation": [
"data":{
"following": true,
"list_id": "29",
"list_name": "list29"
},
"data": {
"following": false,
"list_id": "28",
"list_name": "list28"
}
]
},
{
"items": [
"data_item":{
"description": [
"line1",
"line2",
"line3"
],
"image1": "4367218/img1.jpg",
"item_id": 5600,
"title": "Title 1",
"recommendation_id": 29
},
"data_item":{
"description": [
"line1",
"line2",
"line3"
],
"image1": "342345/img1.jpg",
"item_id": 3600,
"title": "Tite2",
"recommendation_id": 28
}
]
}
型号:
public class Model{
ArrayList<Data> recommendation ;
ArrayList<DataItem> items ;
}
数据模型:
public class Data{
private boolean following ;
private String list_id ;
private String list_name ;
}
DataItem Model:
public class DataItem{
private String description [];
private String image1 ;
private String item_id ;
private String title ;
private String recommendation_id ;
}
答案 1 :(得分:0)
我建议将JSON根目录从数组转换为object:
{
"recommendation": [...],
"items": [...]
}
然后让Retrofit将JSON响应解析为新模型,假设为Response
:
public class Response {
private Recommendation[] recommendation;
private Item[] items;
// your getters
}