gpt4 book ai didi

java - 使用recyclerview和cardview在android Activity 中读取JSON数组

转载 作者:行者123 更新时间:2023-12-02 13:01:38 25 4
gpt4 key购买 nike

我知道如何解析 JSON 对象,如下所示

  {
"users": [{
"id": 2,
"username": "user",
"full_name": "user full name",
"profilePicture": "/images/profileimage.png"
},

{
"id": 2,
"username": "user2",
"full_name": "user2 full name",
"profilePicture": "/images/profileimage2.png"
}
]
}

通过像这样使用recyclerview和cardview调用JSON对象

  try {
JSONObject response = new JSONObject(result);
JSONArray users= response.optJSONArray("users");
feedsList = new ArrayList<>();

for (int i = 0; i < users.length(); i++) {
JSONObject user = users.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(user.optString("full_name"));
item.setThumbnail(user.optString("profilePicture"));
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}

我想在 android Activity 中读取以下 JSON

[
{
"id": 2,
"username": "user",
"full_name": "user full name",
"profilePicture": "/images/profileimage.png",
},

{
"id": 2,
"username": "user2",
"full_name": "user2 full name",
"profilePicture": "/images/profileimage2.png",
}
]

任何人都知道我如何读取这种以 [ 而不是 { 开头的 JSON 可以帮助我

最佳答案

你的错误是你可以使用 posts.length 替换它 users.lenth

        try {

JSONObject response = new JSONObject(result);
JSONArray users= response.optJSONArray("users");
feedsList = new ArrayList<>();

for (int i = 0; i < users.length(); i++) {
JSONObject user = users.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(user.optString("full_name"));
item.setThumbnail(user.optString("profilePicture"));
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}

关于java - 使用recyclerview和cardview在android Activity 中读取JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com