【发布时间】:2017-05-01 09:23:32
【问题描述】:
这是我的 json:
{
"posts": [
{
"id": "c200",
"title": "erfan",
"email": "erfan@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"attachments":[
{
"url":"http://memaraneha.ir/wp-content/uploads/2016/11/light.jpg"
}]},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"attachments":[
{
"url":"http://memaraneha.ir/wp-content/uploads/2016/11/renovate-old-home.jpg"}]
}]
}
我想在attachments 数组中获取title 和url。到目前为止我已经尝试过了。
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonContent jsonContent = new jsonContent(); //my class
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent.title = c.getString("title");
JSONArray attachments=c.getJSONArray("attachments");
for (int j=0;j<attachments.length();j++) {
JSONObject a=attachments.getJSONObject(j);
jsonContent.imgurl=a.getString("url");
}
listcontent.add(jsonContent); //mylist
}
} catch(Exception e) {}
然后我在 TextView 和 ImageView 中显示 title 和 url RecyclerView。在卡片 1 中,我展示了解析后的 json 中的第一个标题和图像,效果很好。但问题出在卡片 2 中,它显示了卡片 1 的标题和图像,无论我们有多少 json 数据,它只是在我的RecyclerView 的所有项目中显示相同的标题和图像。
这是解析 Json 响应的 POJO。
public class jsonContent {
public String title;
public String imgurl;
}
【问题讨论】:
-
我不知道
listcontent是什么,但除非add方法复制其参数,否则您需要为每个post 元素创建一个新的jsonContent对象。您正在为每个帖子添加相同的对象。 -
我从来没有说过任何关于复制的事情。那是塞尔文。我建议将
jsonContent jsonContent = new jsonContent();行移到for循环内。你试过吗? -
Pavneet “请不要回答”部分只是对您对 Ted 的评论(您已删除)的评论...我并不是说您应该真正删除您的答案...跨度>
标签: android json android-json