Skip to content
Serialization

Serialization

The gofhir/models library serializes FHIR resources to JSON and XML. Every generated resource struct implements the standard Go marshaling interfaces, and the library also provides custom functions for FHIR-specific serialization requirements.

Measured over the official example corpora, all 3653 published XML examples round-trip, as do 99.9% of the 8758 JSON ones. See XML Marshaling for what the XML figure does and does not measure.

Serialization Overview

FHIR resources can be exchanged in two wire formats: JSON and XML. The gofhir/models library supports both, with careful attention to the FHIR specification’s requirements for each format.

JSON Serialization

All resource structs implement json.Marshaler and json.Unmarshaler from Go’s standard encoding/json package. This means you can use json.Marshal() and json.Unmarshal() directly with any resource type.

import (
    "encoding/json"
    "github.com/gofhir/models/r4/v2"
)

patient := &r4.Patient{
    Id:           ptrTo("123"),
}
data, err := json.Marshal(patient)

In addition, the library provides r4.Marshal() and r4.MarshalIndent() functions that solve a specific problem with Go’s standard JSON encoder: HTML entity escaping. These custom functions preserve HTML content in FHIR narrative fields exactly as the FHIR specification requires.

XML Serialization

XML serialization is handled through dedicated helper functions in the xml_helpers.go module: MarshalResourceXML(), MarshalResourceXMLIndent() and UnmarshalResourceXML(). Namespace handling, the FHIR convention of encoding primitives as <name value="..."/> attributes, and the XHTML narrative all work. See XML Marshaling.

Polymorphic Deserialization

When working with raw FHIR data where the resource type is not known at compile time, the library provides a resource registry with functions like UnmarshalResource(), GetResourceType(), and NewResource() that enable dynamic dispatch to the correct Go struct based on the resourceType field.

Topics

Quick Comparison

MethodHTML-SafeIndentedUse Case
json.Marshal()NoNoGeneral JSON output without HTML content
json.MarshalIndent()NoYesDebug/display output without HTML content
r4.Marshal()YesNoProduction FHIR JSON output
r4.MarshalIndent()YesYesHuman-readable FHIR JSON output
r4.MarshalResourceXML()N/ANoCompact FHIR XML output
r4.MarshalResourceXMLIndent()N/AYesHuman-readable FHIR XML output
For production systems exchanging FHIR resources, use r4.Marshal() instead of json.Marshal() to ensure narrative XHTML content is preserved correctly. See the Custom Marshal page for details.
Last updated on