Ashish
Ashish

Reputation: 431

Serialising FHIR Resource to JSON using JAVA API

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.

Upvotes: 3

Views: 3323

Answers (2)

PK.Shrestha
PK.Shrestha

Reputation: 120

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

Upvotes: 4

Grahame Grieve
Grahame Grieve

Reputation: 3586

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

Upvotes: 1

Related Questions