Delmon Young Delmon Young - 4 months ago 14
JSON Question

Java - Retrieving nested JSON array key values

I've got a JSON response that looks like this:

USER:[{
"id":"145454",
"name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true,
"caregiverName":"Jones"
}]


I'm trying to create a java method so I can access the key value pairs of the nested
JSONArray
. For example I don't want the entire JSON array I just want to retrieve the doctor name from the
patientInfo
JSON array. Any ideas how I would do this in Java I'm completely stuck here.

This is sudo code but I imagine it would be something like:

String doctorInfo() {
JSONObject obj = new JSONObject(user)
JSONArray arr = obj.getJSONArray("patientInfo")

String doctor = arr.getValue("doctor")
}


And I'd like to be able to access it on the front end by doing

doctorInfo().doctor


Code samples are greatly appreciated.

Answer

The code will be like this:

String doctorInfo(String jsonString) {
    JSONObject obj = new JSONObject(jsonString)
    JSONArray arr = obj.getJSONArray("patientInfo")
    JSONObject patientJSONObject = arr.getJSONObject(0);
    String doctor = patientJSONObject.getString("doctor");
    return doctor;
}

The above code sample assumes you are passing the below string as the parameter.

{ "id":"145454", "name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true, "caregiverName":"Jones" }