问题描述
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”)。我该怎么做?
解决方法
试试下面的代码片段:
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);
}