【问题标题】:How to convert JSONArray which has Key Value to a Map in Java如何将具有键值的 JSONArray 转换为 Java 中的 Map
【发布时间】:2021-08-04 12:49:11
【问题描述】:

我已经能够通过使用 RestAssured 获得一个 Jsonarray 作为响应。但不知道如何将其放入一个 Hashmap 中,其中一个显示指标名称的 String 和一个显示相应值的 Integer。

来自 RestAssured 的回应:

{
    "results": [
        {
            "maximum": 3.858
        },
        {
            "minimum": 5.20
        },
        {
            "number": 249
        }
    ]
}

我想要的是一个包含最大值、最小值和数字及其对应值的地图。 例如:{"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;
    }

【问题讨论】:

    标签: java gson rest-assured


    【解决方案1】:

    这就是我所做的:

    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}
    

    【讨论】:

    • 非常感谢!!这就是我一直在寻找的。干杯
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多