android - 如何访问 JSON 对象中的嵌套数组 (Android)

标签 android arrays json object nested

我的 JSON 的结构是,

"posts":[
    //Post 1.        
    {
        "images":{
            "small":{
                "url": "http://..."
                "width": 64
            },
            "large":{
                "url": "http://..."
                "width": 128
            }
        },

        "caption":"..."
    },

    {
        //Post 2
        "images":{
            "small":{
                "url": "http://..."
                "width": 64
            },
            "large":{
                "url": "http://..."
                "width": 128
            }
        },

        "caption":"..."

     } 
]

我想以字符串的形式从每个帖子中获取,posts -> images -> large -> url

这是我所做的:

JSONArray jsonarray = jsonobject.getJSONArray("posts");

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    JSONArray innerArray1 = jsonobject.getJSONArray("images");
    JSONArray innerArray2 = innerArray1.getJSONArray(0);    //gets "large"
    JSONArray innerArray3 = innerArray2.getJSONArray(1);    //gets "url"
    String finalString = innerArray3.toString();
}

我期望 finalString 中的“url”值,但它最终为空。

我做错了什么?

最佳答案

“images”、“small”、“large”是 JSONObjects(注意大括号),而不是 JSONArrays(方括号),您需要这样提取它们。

JSONArray jsonarray = jsonobject.getJSONArray("posts");

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    JSONObject innerObject1 = jsonobject.getJSONObject("images");
    JSONObject innerObject2 = innerObject1.getJSONObject("large");    //gets "large"
    String finalString = innerObject2.getString("url");
}

关于android - 如何访问 JSON 对象中的嵌套数组 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552793/

相关文章:

android - 如何使用不同的 LayoutParams

android - 如何知道 MenuItem 是在 ActionBar 还是 Overflow

android - 无法显示 JSON 数组,JSONException : No value Error

mysql - 在 MySQL 查询中遍历 JSON

javascript - 比较包含数组的对象属性以找出差异

android - 数据绑定(bind)在 fragment 和 Activity 之间表现出意外

android - ContentResolver 更改图库文件夹名称

c# - Marshal.Copy,将一个 IntPtr 数组复制到一个 IntPtr

php - 为什么我的数组没有用双引号将每个单词括起来?

arrays - 使用谷歌表格中的数据验证从另一本书导入范围