3.1.1Parsers and Serializers

 

HAPI FHIR has built-in support for the FHIR JSON and XML encoding formats.

A built in parser can be used to convert HAPI FHIR Java objects into a serialized form, and to parse serialized data into Java objects. Note that unlike some other frameworks, HAPI FHIR does not have separate parsers and serializers. Both of these functions are handled by a single object called the Parser.

3.1.2Parsing (aka Deserializing)

 

As with many parts of the HAPI FHIR API, parsing begins with a FhirContext object. The FhirContext can be used to request an IParser for your chosen encoding style that is then used to parse.

// Create a FHIR context
FhirContext ctx = FhirContext.forR4();

// The following example is a simple serialized Patient resource to parse
String input = "{" + "\"resourceType\" : \"Patient\","
      + "  \"name\" : [{"
      + "    \"family\": \"Simpson\""
      + "  }]"
      + "}";

// Instantiate a new parser
IParser parser = ctx.newJsonParser();

// Parse it
Patient parsed = parser.parseResource(Patient.class, input);
System.out.println(parsed.getName().get(0).getFamily());

3.1.3Encoding (aka Serializing)

 

As with many parts of the HAPI FHIR API, parsing begins with a FhirContext object. The FhirContext can be used to request an IParser for your chosen encoding style that is then used to serialize.

The following example shows a JSON Parser being used to serialize a FHIR resource.

// Create a FHIR context
FhirContext ctx = FhirContext.forR4();

// Create a Patient resource to serialize
Patient patient = new Patient();
patient.addName().setFamily("Simpson").addGiven("James");

// Instantiate a new JSON parser
IParser parser = ctx.newJsonParser();

// Serialize it
String serialized = parser.encodeResourceToString(patient);
System.out.println(serialized);

// Using XML instead
serialized = ctx.newXmlParser().encodeResourceToString(patient);
System.out.println(serialized);

3.1.3.1Pretty Printing

By default, the parser will output in condensed form, with no newlines or indenting. This is good for machine-to-machine communication since it reduces the amount of data to be transferred but it is harder to read. To enable pretty printed output:

When using the HAPI FHIR Server, pretty printing can be requested by adding the parameter _pretty=true to the request.

// Create a parser
IParser parser = ctx.newJsonParser();

// Indent the output
parser.setPrettyPrint(true);

// Serialize it
String serialized = parser.encodeResourceToString(patient);
System.out.println(serialized);

// You can also chain these statements together
ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);

3.1.3.2Encoding Configuration

There are plenty of other options too, that can be used to control the output by the parser. A few examples are shown below. See the IParser JavaDoc for more information.

// Create a parser
IParser parser = ctx.newJsonParser();

// Blacklist certain fields from being encoded
parser.setDontEncodeElements(Sets.newHashSet("Patient.identifier", "Patient.active"));

// Don't include resource narratives
parser.setSuppressNarratives(true);

// Use versioned references for these reference elements
parser.setDontStripVersionsFromReferencesAtPaths("Patient.organization");

// Serialize it
String serialized = parser.encodeResourceToString(patient);
System.out.println(serialized);

3.1.3.3Summary Mode

For each resource type, the FHIR specification defines a collection of elements which are considered "summary elements". These are marked on the individual resource views using a Sigma (Σ) symbol next to the element names. See the Patient Resource Definition for an example, looking for this symbol on the page.

If the parser is configured as shown below, only the summary mode elements will be included in the encoded resource.

When using the HAPI FHIR Server, summary mode can be requested by adding the parameter _summary=true to the request.

// Create a parser
IParser parser = ctx.newJsonParser();

// Instruct the parser to only include summary elements
parser.setSummaryMode(true);

// If you need to, you can instruct the parser to override
// the default summary elements by adding and/or removing
// elements from the list of elements it will include. This
// is typically not needed, but it's shown here in case you
// need to do this:
// Include a non-summary element in the summary view.
parser.setEncodeElements("Patient.maritalStatus");
// Exclude a summary element even though it would normally
// be included.
parser.setDontEncodeElements("Patient.name");

// Serialize it
String serialized = parser.encodeResourceToString(patient);
System.out.println(serialized);

3.1.4Global Parser Configuration

 

It is possible to configure a number of parser settings globally for a given FhirContext, meaning that they will apply to all parsers that are created by that context. This is especially useful for HAPI FHIR Clients and HAPI FHIR Servers, where parsers are created by the client/server internally using the given FhirContext.

FhirContext ctx = FhirContext.forR4();

// Request the ParserOptions, which store global config
// settings applied to all parsers coming from the given
// context.
ParserOptions parserOptions = ctx.getParserOptions();

// Never strip resource reference versions for the following
// paths
parserOptions.setDontStripVersionsFromReferencesAtPaths(
      "AuditEvent.entity.reference", "Patient.managingOrganization");

// Never strip any resource reference versions (setting this
// to false would make the setting above redundant since this
// setting applies to all paths)
parserOptions.setStripVersionsFromReferences(false);

// Even in summary mode, always include extensions on the
// root of Patient resources.
parserOptions.setEncodeElementsForSummaryMode("Patient.extension");

// Create a parser and encode, with the global config applied.
IParser parser = ctx.newJsonParser();
String encoded = parser.encodeResourceToString(patient);