Parsing of JSON file may get bit complicated and confusing if you are not sure which library to use. There are different ways and Implementation available however I chose to use GSON library since it looked feasible for the JSON file which I was trying to parse. Sample JSON is provided below
In this example, I have saved my response in a file for demonstration.
Objective: Get the value of PatientID from this JSON
{
"response": {
"body": {
"patients": {
"patient": [
{
"patientID": "ALM22346789",
"submittedStatus": "In Progress",
"patientType": "Inpatient",
"submissionDate": "2020-10-15"
}
]
}
},
"status": {
"statusCode": "200",
"statusMessage": {
}
}
}
}
Imports used:
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
Step1:
Read the file from the saved location and store it in JsonObject
JsonObject myobject = (JsonObject) new JsonParser().parse(new FileReader("MyFilePath"));
Step2: Hold the "response" in a JSON Object
JsonObject response = (JsonObject) myobject.get("response");
Step3: Drill down further and store the "body" and "patient" in JSON Object
JsonObject body = (JsonObject) response.get("body");
JsonObject patients= (JsonObject) body.get("patients");
Step4: "patient" tag is in a Array hence we will store it in Array Object
JsonArray patientbody= (JsonObject) patients.get("patient");
JsonObject patient0= patientbody.get(0).getAsJsonObject();
Step5: Next we will fetch the "patientID"
String patientID =caseBody0.get("patientID").getAsString(); System.out.println(patientID);
OutPut: (as printed in console)
ALM22346789
Top comments (0)