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.
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
| Method | HTML-Safe | Indented | Use Case |
|---|---|---|---|
json.Marshal() | No | No | General JSON output without HTML content |
json.MarshalIndent() | No | Yes | Debug/display output without HTML content |
r4.Marshal() | Yes | No | Production FHIR JSON output |
r4.MarshalIndent() | Yes | Yes | Human-readable FHIR JSON output |
r4.MarshalResourceXML() | N/A | No | Compact FHIR XML output |
r4.MarshalResourceXMLIndent() | N/A | Yes | Human-readable FHIR XML output |
r4.Marshal() instead of json.Marshal() to ensure narrative XHTML content is preserved correctly. See the Custom Marshal page for details.