Search code examples
gsonhl7-fhirhapihapi-fhir

Cast json to hapi fhir object


I have an appointment json which I need to cast to DSTU2 HAPI FHIR json object. Any standard library available for the same ? Google gson library works but does not give value to object in fields

{
  "resourceType": "Appointment",
  "id": "",
  "status": "proposed",
  "reason": {
    "text": "Regular checkup"
  },
  "description": "",
  "slot": [
    {
      "reference": "bfgf5dfdf4e45g"
    }
  ],
  "comment": "Regular yearly visit",
  "participant": [
    {
      "actor": {
        "reference": "9sdfsndjkfnksdfu3yyugbhjasbd"
      },
      "required": "required"
    },
    {
      "actor": {
        "reference": "78hjkdfgdfg223vg"
      },
      "required": "required"
    },
    {
      "actor": {
        "reference": "sdfs3df5sdfdfgdf"
      },
      "required": "required"
    }
  ]
}

Need to convert above json to ca.uhn.fhir.model.dstu2.resource.Appointment class for which I use

Appointment appointment = new Gson().fromJson(map.get("appointment"), Appointment.class);

but it gives appointment object with empty fields


Solution

  • Rather than using GSON directly, it's better to use HAPI FHIR api which internally uses GSON to parse the JSON. Maven dependency:

    <dependency>
       <groupId>ca.uhn.hapi.fhir</groupId>
       <artifactId>hapi-fhir-base</artifactId>
       <version>2.1</version>
    </dependency>
    <dependency>
       <groupId>ca.uhn.hapi.fhir</groupId>
       <artifactId>hapi-fhir-structures-dstu3</artifactId>
       <version>2.1</version>
    </dependency>
    

    // More details on how to setup gradle and maven to get the HAPI fhir dependency added to your project please check http://hapifhir.io/download.html

    Snippet:

    FhirContext ourFhirCtx = FhirContext.forDstu3();
    IParser parser=ourFhirCtx.newJsonParser().setPrettyPrint(true);
    String string="{\"resourceType\":\"Appointment\",\"id\":\"\",\"status\":\"proposed\",\"reason\":{\"text\":\"Regular checkup\"},\"description\":\"\",\"slot\":[{\"reference\":\"bfgf5dfdf4e45g\"}],\"comment\":\"Regular yearly visit\",\"participant\":[{\"actor\":{\"reference\":\"9sdfsndjkfnksdfu3yyugbhjasbd\"},\"required\":\"required\"},{\"actor\":{\"reference\":\"78hjkdfgdfg223vg\"},\"required\":\"required\"},{\"actor\":{\"reference\":\"sdfs3df5sdfdfgdf\"},\"required\":\"required\"}]}";
    Appointment parsed=parser.parseResource(Appointment.class,string);