DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Suparna Das
Suparna Das

Posted on

How to parse complex Json response file in Java

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": {

      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Imports used:
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

Enter fullscreen mode Exit fullscreen mode

Step1:
Read the file from the saved location and store it in JsonObject

JsonObject myobject = (JsonObject) new JsonParser().parse(new FileReader("MyFilePath"));

Enter fullscreen mode Exit fullscreen mode

Step2: Hold the "response" in a JSON Object

JsonObject response = (JsonObject) myobject.get("response");

Enter fullscreen mode Exit fullscreen mode

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");

Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

Step5: Next we will fetch the "patientID"

String patientID =caseBody0.get("patientID").getAsString(); System.out.println(patientID);

Enter fullscreen mode Exit fullscreen mode

OutPut: (as printed in console)

ALM22346789
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Create an Account! The only reason people scroll to the bottom... Β 
is because they want to read more.

Create an account to bookmark, comment, and react to articles that interest you.