How to access nested elements of a JSON array using only GSON with Java
No idea why you thought you'd need a new JsonParser
when the JSON has already been parsed.
Just so we can all see what you're parsing, here is a part of it:
{ "page": 1, "per_page": 10, "total": 99, "total_pages": 10, "data": [ { "id": 1, "timestamp": 1565637002408, "diagnosis": { "id": 3, "name": "Pulmonary embolism", "severity": 4 }, "vitals": { "bloodPressureDiastole": 154, "bloodPressureSystole": 91, "pulse": 125, "breathingRate": 32, "bodyTemperature": 100 }, "doctor": { "id": 2, "name": "Dr Arnold Bullock" }, "userId": 2, "userName": "Bob Martin", "userDob": "14-09-1989", "meta": { "height": 174, "weight": 172 } }, ... ]}
Java is an Object-Oriented language. Use it! Create a class for store the data values, then have a single List<Data>
.
List<Data> dataList = new ArrayList<>();
You already got to iterate the data
, so let's start there.
Don't lookup the object in the array multiple times. Bad for performance, and bad for the readability of the code.
JsonArray dataArray = convertedObject.getAsJsonArray("data");for (JsonElement dataElem : dataArray) { System.out.println(dataElem); JsonObject dataObj = dataElem.getAsJsonObject(); int id = dataObj.get("id").getAsInt(); long timestamp = dataObj.get("timestamp").getAsLong(); String userDob = dataObj.get("userDob").getAsString(); // Now for the good stuff JsonObject vitals = dataObj.getAsJsonObject("vitals"); int bpDiastole = vitals.get("bloodPressureDiastole").getAsInt(); int bpSystole = vitals.get("bloodPressureSystole").getAsInt(); Data data = new Data(); data.setId(id); data.setTimestamp(timestamp); data.setBirthDate(userDob); data.setBpd(bpDiastole); data.setBps(bpSystole); dataList.add(data);}
where the Data
class is:
public class Data { private int id; private long timestamp; private String birthDate; private int bpDiastole; private int bpSystole; // Getters and setter here}