3

I am trying to convert an FHIR Resource or ResourceOrFeed Object to the JSON String. I could not find any API methods available in the Java Implementation for this.

There are serializers available for .NET api but similar API is not available for Java implementation.

Any pointers on how to convert an ResourceOrFeed object to Actual String JSON representation?

The default conversion from Spring Jackson converter is working for me but it is not outputting the correct JSON and I dont want to write a custom Object mapper.

Ashish
  • 421
  • 9
  • 22

2 Answers2

4

Try HAPI fhir : http://hapifhir.io/

Maven dependency to add in the pom file:

<dependency>
        <groupId>ca.uhn.hapi.fhir</groupId>
        <artifactId>hapi-fhir-base</artifactId>
        <version>2.2-SNAPSHOT</version>
</dependency>

Java snippet:

import org.hl7.fhir.dstu3.model.*;
import ca.uhn.fhir.context.FhirContext;
// for other imports use your IDE. 

public void printPatientJSON() {
    FhirContext ourCtx = FhirContext.forDstu3();

    Patient patient = new Patient();
    patient.addName().addFamily("PATIENT");

    // now convert the resource to JSON
    String output = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);

    System.out.println(output);
}
Marouane Gazanayi
  • 5,063
  • 6
  • 39
  • 58
PK.Shrestha
  • 120
  • 9
1

This is one way it can be done:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
new org.hl7.fhir.instance.formats.JsonComposer().compose(bytes, feed, true);
return new String(bytes.toByteArray());
Grahame Grieve
  • 3,538
  • 3
  • 15
  • 17