如何在Java中将具有Key Value的JSONArray转换为Map



我已经能够从使用RestAssured获得Jsonarray作为响应。但不知道如何将其放入Hashmap中,其中字符串显示度量的名称,整数显示相应的值。

RestAssured的响应:
{
"results": [
{
"maximum": 3.858
},
{
"minimum": 5.20
},
{
"number": 249
}
]
}

我想要的是一个包含max, min &编号及其对应的值。例:{"max": 3.858, "min": 5.20, "number": 249 }

到目前为止,我已经尝试了下面的代码,但它似乎不工作。如有任何帮助,不胜感激。
public static HashMap<String, String> getMinMaxCount(String URL, String query) {
JsonObject res = getNewRelicAPIResponse(URL, query);
HashMap<String, String> map = null;
//System.out.println("Response is : " + res);
JsonArray metricsArray = res.get("results").getAsJsonArray();
int arraySize = metricsArray.size();
String[] strArr = new String[arraySize];
for (int i = 0; i < arraySize; i++) {
strArr[i] = String.valueOf(metricsArray.get(i));
//Create a Hashmap & append the Max, Min & Count
map  = new HashMap<>();
//            String[] tokens = strArr[i].split(":");
//            String[] tokens2 = tokens[1].split("}");
map.put("max",strArr[i]);
}
return map;
}

我就是这么做的:

String res = ... //get response from API
JsonPath jsonPath = new JsonPath(res);
List<Map<String, Object>> list = jsonPath.getObject("results", new TypeRef<>(){});
System.out.println(list);
//[{maximum=3.858}, {minimum=5.2}, {number=249}]
Map<String, String> resultMap = new HashMap<>();
for (Map<String, Object> mapInList : list) {
for (Map.Entry<String, Object> entryOfMapInList : mapInList.entrySet()) {
resultMap.put(entryOfMapInList.getKey(), entryOfMapInList.getValue().toString());
}
}
System.out.println(resultMap);
//{number=249, maximum=3.858, minimum=5.2}

最新更新