如何在java中创建嵌套的HashMap

时间:2016-07-15 10:08:08

标签: java collections hashmap

我正在尝试将匿名hashmap放入另一个hashmap: -

Map<String, Object> requestBody=new HashMap<String, Object>();
requestBody.put("UPSSecurity", new HashMap<String, Object>().put("username","rohan"));
System.out.println(requestBody);

输出是: -

{UPSSecurity=null}

2 个答案:

答案 0 :(得分:1)

请使用这种方式来定义嵌套的Hashmap。

    Map<String, Object> requestBody=new HashMap<String, Object>();
    Map<String,Object> userdetails=new HashMap<String, Object>();
    userdetails.put("username","rohan");
    requestBody.put("UPSSecurity",userdetails );
    System.out.println(requestBody);

输出:

  

{UPSSecurity = {用户名=罗汉}}

答案 1 :(得分:0)

你也可以这样做。

Map<String, Object> requestBody=new HashMap<String, Object>();
requestBody.put("UPSSecurity", new HashMap<String, Object>());
requestBody.get("UPSSecurity").put("username","rohan");