嵌套的HashMap with Array,JAVA

时间:2017-01-06 21:07:27

标签: java hashmap

我有以下hashMap:

{"success":true,
 "message":"Profile retrieved successfully",
 "data":{
     "address":[{
        "objectId":"6ItcdQGBFu",
        "street":"6782 NW 102nd St",
        "aptSuite":"782",
        "state":"FL",
        "zipCode":"33762",
        "city":"Brickell",
        "type":"Home"},{
        "objectId":"yyRA9M2gk1", 
        "street":"7828 NW Boston Rb",
        "state":"Massachusetts",
        "zipCode":"33178",
        "city":"Boston",
        "type":"Office"}
     ]
    }
}

如果我想访问“消息”,我会写下面的代码:

    object.get("message");

或者,如果我想打印它:

    object.get("message").toString();

我想知道如何通过“地址”对象进行迭代和访问。

1 个答案:

答案 0 :(得分:0)

假设这是一堆嵌套的HashMaps(并且“地址”指向包含一个项目的列表,根据您的示例),您可以通过

访问消息中的值
object.get("data").get("address").get(0).get("street")

你可以通过

遍历所有字段
HashMap<String, String> addressObj = object.get("data").get("address").get(0);
for (Map.Entry<String, String> entry : addressObj.keySet()) {
    String key = entrey.getKey();
    String value = entry.getValue();
    // your code here
}