【发布时间】:2017-10-17 05:08:23
【问题描述】:
我写了下面的代码,它给了我以下输出:
String jsonInString = "NORESPONSE";
List<Map<String , String>> detailsArray = new ArrayList<Map<String,String>>();
JSONObject json = new JSONObject();
Map<String, String> details = new HashMap<String, String>();
for (int i = 0; i < split.length; i++) {
String entry = split[i];
j++;
String entrySplit[] = entry.split("\\:");
details.put("PrimaryEmail", entrySplit[0]);
details.put("DisplayName", entrySplit[1]);
allEntries.put("Entry " + j , details);
//detailsArray.add(i, details);
}
json.putAll(allEntries);
jsonInString = json.toJSONString();
logger.info(jsonInString);
输出:
{
"Entry 2": {
"DisplayName": "OICT-Focal Points All",
"PrimaryEmail": "oict-oict-globalvtc@un87.org"
},
"Entry 3": {
"DisplayName": "OICT-Focal Points All",
"PrimaryEmail": "oict-oict-globalvtc@un87.org"
},
"Entry 1": {
"DisplayName": "OICT-Focal Points All",
"PrimaryEmail": "oict-oict-globalvtc@un87.org"
}
}
但是,我想要以下类型的输出。我的代码需要进行哪些更改?如果有人可以帮助我,那就太好了。提前致谢
[{"DisplayName":"OICT-Focal Points All","PrimaryEmail":"oict-oict-globalvtc@un87.org"},{"DisplayName":"OICT-Focal Points All","PrimaryEmail":"oict-oict-globalvtc@un87.org"},{"DisplayName":"OICT-Focal Points All","PrimaryEmail":"oict-oict-globalvtc@un87.org"}]
【问题讨论】:
-
为什么不在循环中创建
JsonObject并将它们添加到JsonArray而不是hashmap? -
由于 JSONObject 扩展了 HashMap,因此每个属性都需要一个键/值对。您可能会做的最好的事情是设置一个像“条目”这样的属性,并将 detailsArray 作为值。 (当然,这需要取消对 detailsArray.add 行的注释)。然后你会调用 json.put("entries", detailsArray),你的输出会是 {"entries": [...]}。如果您不喜欢使用 JSONObject,您可以使用 Jackson 库 (github.com/FasterXML/jackson) 中的 ObjectMapper。我更喜欢@Pete 的建议!
-
嗨皮特,你能分享我的示例代码
标签: java arrays json arraylist hashmap