【问题标题】:How to fetch value of a key from an Array List which has JSON objects如何从具有 JSON 对象的数组列表中获取键的值
【发布时间】:2020-12-26 11:57:30
【问题描述】:
List<String>ownerLst= new ArrayList<String>();
ownerLst= Util.extractListFromResponse(apiResponse, "", "", "owner");

public static List <String>extractListFromResponse(Response apiResponse, String keyToMatch, String valueToMatch, String getValueOfKey) {
        List<String> currLst = new ArrayList<String>();
        JSONObject json;
        try {
            json = (JSONObject) parser.parse(apiResponse.asString());
            String str;
            if (keyToMatch == "" && valueToMatch == "") {
                str = "$..results[*]." + getValueOfKey.trim();
            } else {
                str = "$..results[?(@." + keyToMatch.trim() + "==\'" + valueToMatch.trim() + "\')]."
                        + getValueOfKey.trim() + "";
            }
            
            currLst = JsonPath.read(json, str);
            logger.info("extractListFromResponse - Current List: " + currLst);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return currLst;
    }

currLst 返回 this- [{"firstname":"xxx","inactive":false] // 一个 JSON 对象

所以,ownerLst 有 [{"firstname":"xxx","inactive":false] // 一个 JSON 对象

现在,我想获取键“firstname”的值(“xxx”)。我该怎么做?

【问题讨论】:

    标签: json rest-assured rest-assured-jsonpath


    【解决方案1】:

    试试下面的 sn-p :

     JSONParser jp = new JSONParser();
        Object object = jp.parse("[{\"firstname\":\"xxx\",\"inactive\":false}]");
        List<JSONObject> objects=null;
        if ( object instanceof JSONArray) {
             objects = (JSONArray) object;
        }
    
        for ( JSONObject jsonObject :  objects)
         {
             Object name =  jsonObject.get("firstname");
             System.out.println(name);
         }
    

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多