【发布时间】:2018-01-24 09:25:21
【问题描述】:
我已将值 json 数组放入哈希映射,但最后一个值是正确的。我仍然不清楚使用哈希映射、列表和数组列表。我的代码:
Map<String, Object> departmentPHSSuportEmail = new HashMap<String, Object>();
Map<String, Object> subSourceMap = null;
List<Map<String , Object>> myMap = new ArrayList<Map<String,Object>>();
subSourceMap = new HashMap<>();
subSourceMap.put("name", "bobby");
subSourceMap.put("address", "xxx.xxxx@xxx.co.id");
subSourceMap.put("name", "2sadasd");
subSourceMap.put("address", "xxx.xxxx@xxx.co.id");
subSourceMap.put("name", "ggfgf");
subSourceMap.put("address", "xxx.xxxx@xxx.co.id");
myMap.add(0, subSourceMap);
myMap.add(1, subSourceMap);
myMap.add(2, subSourceMap);
Map<String, Object> attachment = new HashMap<String, Object>();
attachment.put(ApplicationConstanta.MsExchange.TYPE, "");
attachment.put(ApplicationConstanta.MsExchange.VALUE, "");
departmentPHSSuportEmail.put(ApplicationConstanta.EmailForwardString.ATTACHMENT, attachment);
Map<String, Object> subSource = new HashMap<String, Object>();
subSource.put(ApplicationConstanta.MsExchange.TYPE, ApplicationConstanta.MsExchange.STRING);
subSource.put(ApplicationConstanta.MsExchange.VALUE, myMap);
departmentPHSSuportEmail.put(ApplicationConstanta.EmailForwardString.SUB_SOURCE, subSource);
System.out.println("JSON : " + JsonUtil.toJson(departmentPHSSuportEmail));
结果:
JSON : {
"Attachment" : {
"type" : "",
"value" : ""
},
"SubSource" : {
"type" : "string",
"value" : [ {
"address" : "xxx.xxxx@xxx.co.id",
"name" : "ggfgf"
}, {
"address" : "xxx.xxxx@xxx.co.id",
"name" : "ggfgf"
}, {
"address" : "xxx.xxxx@xxx.co.id",
"name" : "ggfgf"
} ]
}
}
为什么“值”对象中的值都一样?我已经提出了不同的价值。如何解决这个问题呢?谢谢
【问题讨论】:
-
您在
myMap中添加了三次subSourceMap。如果要添加三张不同的地图,则需要添加三张不同的地图,而不是三张地图。 -
如果你不熟悉 hashmaps、lists 等是如何工作的,那么你应该专注于这些,而不是把 json 弄乱。
subSourceMap.put("name", whatever);将覆盖您之前为键"name"设置的任何值。这意味着subSourceMap将仅包含最后一个值,并且将 same 映射 3 次添加到列表中只会导致:具有 3 个完全相同的元素的列表(并且当您更改您更改所有内容的内容)。