【问题标题】:Converting HashMap into JSONArray, Values are not coming properly将 HashMap 转换为 JSONArray,值不正确
【发布时间】:2018-07-03 09:08:35
【问题描述】:

我收到来自 Elasticsearch 的重复响应,以避免我使用 Hashmap 实现并将 put 的所有值放入 HashMap 对象中。

然后遍历HashMap 对象以转换为 JSONArray。

我从distinctObjects(HashMap 对象)获得了一条独特的记录。但是如果转换成 JSONArray 之后,JSONArray 的长度显示为2,它应该是1,并且正在打印 JSONArray,如下所示。

JSONArray --->[{"code":"VA1125-GGA-1","id":"code"},{"code":"12816","id":"id"}]

预期结果应该是:

JSONArray --->[{"code":"VA1125-GGA-1","id":"12816"}]

请在下面找到我的代码。

JSONObject responseObj;
JSONArray responseArray = new JSONArray();
Map<String, Object> distinctObjects = null;
SearchHit[] searchHits2 = searchResponse2.getHits().getHits();
for (SearchHit hit2 : searchHits2) {
    Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
    distinctObjects = new HashMap<String, Object>();
    distinctObjects.put("id", sourceAsMap2.get("id").toString());
    distinctObjects.put("code", sourceAsMap2.get("code").toString());
}               

Iterator it = distinctObjects.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
    responseObj = new JSONObject();
    responseObj.put("id", pair.getKey());
    responseObj.put("code", pair.getValue());
    responseArray.put(responseObj);
    it.remove(); // avoids a ConcurrentModificationException
}

System.out.println("Link ID List Size --->"+responseArray.length());
System.out.println("JSONArray --->"+responseArray.toString());

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example

标签: java json elasticsearch collections


【解决方案1】:

您似乎将codeid 作为顶级条目添加到您的 distinctObjects 映射中,这就是您要返回两个对象的原因。假设您想根据 ID 进行重复数据删除,您的第一个循环应该如下所示:

for (SearchHit hit2 : searchHits2) {
    Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
    distinctObjects = new HashMap<String, Object>();
    distinctObjects.put(sourceAsMap2.get("id"), sourceAsMap2.get("code").toString());
}    

这将为您在distinctObjects 中为每个值为code 的唯一ID 提供一个条目。

如果您希望在下游处理中需要的不仅仅是code,还可以添加sourceAsMap2 作为distinctObjects 中的值以保持完整响应。

【讨论】:

  • 非常感谢,我做了,像这样下游处理Collection&lt;Object&gt; values = distinctObjects.values(); JSONArray jsonArray = new JSONArray(values); for(int i=0;i&lt;jsonArray.length();i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); responseObj = new JSONObject(); responseObj.put("id", jsonObj.optString("id")); responseObj.put("code", jsonObj.optString("code")); responseArray.put(responseObj); }
猜你喜欢
  • 2016-02-09
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 2013-06-06
  • 2016-06-05
  • 2015-07-30
相关资源
最近更新 更多