Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a Value in Json Array

Tags:

java

json

parsing

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!

like image 620
InfoEngi Avatar asked Jun 14 '26 13:06

InfoEngi


1 Answers

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

like image 165
Pradeep Simha Avatar answered Jun 17 '26 02:06

Pradeep Simha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!