InfoEngi InfoEngi - 3 months ago 8
JSON Question

Searching a Value in Json Array

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
}


After getting the response, i have converted it to a string:

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;
}


Now, i want to search a projectname (e.g. "Testproject2") in the String and want to have the attributes "id" and "name" as well.

i have tried it with

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);


But the problem is, that i always get "org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray". I think the problem is, because my json is an array, but how can i get the attributes?

Best Regards!

Answer

Your elements is a JSONArray, but you are trying to parse it as a JSONObject, change your code like this:

JSONObject jsonObject = new JSONObject(PaListContent);
JSONArray myResponse = jsonObject.getJSONArray("elements");
//JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");

ArrayList<String> list = new ArrayList<String>();

for(int i=0; i<myResponse.length(); i++){
    list.add(myResponse.getJSONObject(i).getString("name"));
}

System.out.println(list);

This will work as expected

Comments