Need to extract specific element in a json array using java

Viewed 33

Need to extract the value of "id" where name is "SPECIAL" using Java. So, in below case we need to return "TMN456":

{
  "data": {
    "id": "12345",
   "details": [
      {
        "id": "ABC123",
        "name": "NORMAL",
        "job": "JOB1"
      },
      {
        "id": "PQR098",
        "name": "BLUE COLLAR",
        "job": "JOB2"
      },
      {
        "id": "XYZ567",
        "name": "HIGH-PAYING",
        "job": "JOB3"
      },
      {
        "id": "TMN456",
        "name": "SPECIAL",
        "job": "JOB4"
      }
    ]
  }
}

We can use json.org dependency in pom.

1 Answers

Here, you can do this as follows:

public static String getId(JSONArray detailArray, String name) {
    for(int i = 0; i < detailArray.length(); i++) {
        if(detailArray.getJSONObject(i).getString("name").equals(name)) {
            return detailArray.getJSONObject(i).getString("id");
        }
    }
    return null;
}

And initialise the json data into json array as follows

JSONArray detailArray = new JSONObject(json).getJSONObject("data").getJSONArray("details");
System.out.println("ID :"+getId(detailArray, "SPECIAL")); //O/p=TMN456
Related