Reputation: 2053
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.
Upvotes: 1
Views: 3357
Reputation: 4702
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" }
Upvotes: 1