i have the following json response:
{
"elements":
[
{
"id": "1234",
"Key": "1234-name2",
"name": "name2",
"projectName": "TestProject",
},
{
"id": "5678",
"applicationKey": "5678-name2",
"name": "name2",
"projectName": "TestProject2",
},
{
"id": "9101112",
"applicationKey": "9101112-name3",
"name": "name3",
"projectName": "TestProject3",
},
],
"totalSize": 3
}
在获取响应后,我将其转换为字符串:
String PaListContent = getContent(PaListResponse);
private static String getContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity == null) return null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = reader.readLine();
reader.close();
return line;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
现在,我想在字符串中搜索一个项目名称(例如"Testproject2"),并希望同时获取"id"和"name"属性。
我已经尝试了以下方法:
JSONObject jsonObject = new JSONObject(PaListContent);
JSONObject myResponse = jsonObject.getJSONObject("elements");
//JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<tsmresponse.length(); i++){
list.add(tsmresponse.getJSONObject(i).getString("name"));
}
System.out.println(list);
但问题是,我总是得到“org.json.simple.JSONObject无法转换为org.json.simple.JSONArray”的错误。我认为问题是因为我的json是一个数组,但是如何获取属性呢?
最好的问候!
System.out.println(jsonObject)
查看它实际包含了什么。 - Young Emil