【发布时间】: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