Skip to main content
Docs/Read and write FHIR JSON
On this page ⌄
Usage guide

Read and write FHIR JSON

Encode and decode FHIR JSON with kotlinx.serialization, handle decoding errors, limit untrusted input, and choose Json options.

UPDATED

Goal and scope​

Kotlin FHIR reads and writes JSON with kotlinx.serialization. Every class has a generated serializer, and you use a standard Json instance. One Json instance can be shared across threads and coroutines. This page covers encoding, decoding, error handling, untrusted input, and Json options.

Encode and decode​

import dev.ohs.fhir.model.r4.Patient
import dev.ohs.fhir.model.r4.Resource
import kotlinx.serialization.json.Json

val json = Json { prettyPrint = true }

val text = json.encodeToString(patient)
val patientAgain = json.decodeFromString<Patient>(text)

If you do not know the resource type in advance, for example in a server response, decode as Resource. The library reads the resourceType property and returns an instance of the matching class.

val resource: Resource = json.decodeFromString<Resource>(text)

Handle decoding failures​

Decoding throws one of two exceptions.

  • SerializationException if the JSON is malformed, a required element is missing, a property is unknown, or the resourceType is unknown.
  • IllegalArgumentException if an element with a required binding has a code that is not in its ValueSet.

SerializationException is a subclass of IllegalArgumentException. Catch IllegalArgumentException to handle both.

import dev.ohs.fhir.model.r4.Resource

try {
val resource = json.decodeFromString<Resource>(text)
} catch (e: IllegalArgumentException) {
// The JSON is not valid for this FHIR model.
// This also catches SerializationException.
}

Limit untrusted input​

The library does not limit how deeply JSON is nested or how large a decimal is. Two kinds of input can use up memory or CPU.

  • Deeply nested JSON. Nested elements, such as extensions inside extensions, are decoded recursively. Very deep nesting can cause a StackOverflowError.
  • Very large decimals. A decimal with tens of thousands of digits, or arithmetic with a very large exponent such as 1e1000000, can cause high CPU use or an OutOfMemoryError. This comes from the bignum library that FhirDecimal uses.

If you decode JSON from a source you do not control, check its size, nesting depth, and number lengths before decoding.

Expect normalized output​

When you decode JSON and encode it again, the output can differ from the original text. For example, properties are reordered and a +00:00 offset becomes Z. The data has the same meaning. Do not compare FHIR JSON as text. Decode both sides and compare the resources with ==.

How the model maps FHIR explains what the serializers change and why.

Json options​

This configuration suits JSON from servers and other systems.

import kotlinx.serialization.json.Json

val json = Json {
prettyPrint = true // indent the output
ignoreUnknownKeys = true // skip properties the model does not have
}

Without ignoreUnknownKeys, a single unknown property makes decoding fail.

Do not turn on isLenient for data you do not control. It accepts JSON that is not valid, such as unquoted strings, so bad data decodes without an error.

Some options do not work with the generated serializers.

  • explicitNulls, encodeDefaults, useAlternativeNames, and classDiscriminator have no effect.
  • useArrayPolymorphism and namingStrategy produce JSON that is not valid FHIR. Do not use them.

Other formats​

JSON is the only FHIR format the library supports and tests. FHIR XML and Turtle are not supported. You can use other kotlinx.serialization formats, such as ProtoBuf, but the output is not a FHIR format. ProtoBuf output has not been tested for compatibility with Google's FHIR protocol buffers.

Next step​

Extract search parameters covers getting search values from resources without a FHIRPath engine.