0
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 returns this- [{"firstname":"xxx","inactive":false] // A JSON object

So, ownerLst has [{"firstname":"xxx","inactive":false] // A JSON object

Now, I want to fetch the value("xxx") of the key "firstname". How do I do that?

Dhruv Bhatnagar
  • 121
  • 5
  • 17

1 Answers1

0

try the below snippet :

 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);
     }
Karan
  • 443
  • 5
  • 14