简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM