My Rest服务产生如下响应
{
"feeds": [
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/image1.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image1.jpg"
]
},
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/mage2.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image2.jpg"
]
}
]
}
我如何用Gson解析它。在我的Android客户端中,我也有相同的Feed类女巫,这个JSON是生成的 注意:我已经将Spring引导用于我的其余API,并且这个JSON是使用ResponseEntity生成的。
答案 0 :(得分:1)
首先,确保您拥有有效的JSON。以上情况无效。
如果json对象包含单个元素,则不需要在此之后放置逗号。 (在主持人和上传者对象中 id 后面的逗号)。您需要删除它。还需要在 moderatedOn 值之后放置一个逗号。
现在有了一个有效的,你有一个饲料类。为了将您的json 供稿数组映射到您的列表中。您需要执行以下操作。
Gson gson = new Gson();
Type feedsType = new TypeToken<ArrayList<Feed>>(){}.getType();
List<Feed> feedList = gson.fromJson(yourJsonResponseArray, feedsType);
你的班级必须是这样的。 饲料类
public class Feed
{
private String id;
private String imagePath;
private Moderator moderator;
private String description;
private String rejected;
private Uploader uploader;
private String moderatedOn;
private String[] imagePaths;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getImagePath ()
{
return imagePath;
}
public void setImagePath (String imagePath)
{
this.imagePath = imagePath;
}
public Moderator getModerator ()
{
return moderator;
}
public void setModerator (Moderator moderator)
{
this.moderator = moderator;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRejected ()
{
return rejected;
}
public void setRejected (String rejected)
{
this.rejected = rejected;
}
public Uploader getUploader ()
{
return uploader;
}
public void setUploader (Uploader uploader)
{
this.uploader = uploader;
}
public String getModeratedOn ()
{
return moderatedOn;
}
public void setModeratedOn (String moderatedOn)
{
this.moderatedOn = moderatedOn;
}
public String[] getImagePaths ()
{
return imagePaths;
}
public void setImagePaths (String[] imagePaths)
{
this.imagePaths = imagePaths;
}
}
主持人类
public class Moderator
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
上传者类
public class Uploader
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}