【发布时间】:2016-08-31 11:43:49
【问题描述】:
我有以下 json 响应:
{
"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 cannot be cast to org.json.simple.JSONArray”。我认为问题是,因为我的 json 是一个数组,但是我怎样才能获得属性呢?
最好的问候!
【问题讨论】:
-
试试
System.out.println(jsonObject)看看它到底包含什么