【问题标题】:Array of hashmap output in jsonjson 中的 hashmap 输出数组
【发布时间】: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


【解决方案1】:

根据@Pete 的评论,这里是示例代码(未经测试):

String jsonInString = "NORESPONSE";
JSONArray json = new JSONArray();
JSONObject jsonObj;

for (int i = 0; i < split.length; i++) {
    String entry = split[i];
    jsonObj = new JSONObject();

    String entrySplit[] = entry.split("\\:");
    jsonObj.put("PrimaryEmail", entrySplit[0]);
    jsonObj.put("DisplayName", entrySplit[1]);

    json.put(jsonObj);
}

jsonInString = json.toJSONString();
logger.info(jsonInString);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多