> For the complete documentation index, see [llms.txt](https://php-fhir-tools.ardenexal.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://php-fhir-tools.ardenexal.net/serialization/json.md).

# JSON Serialization

`serializeToJson()` turns a FHIR model object into a JSON string. `deserializeFromJson()` reads JSON back into a typed model object. The round-trip below builds a `PatientResource`, serializes it, and deserializes it back.

FHIR model classes use promoted public properties, so you set values through the constructor's named arguments or by assigning the public property. There are no `setX()` setters.

```php
<?php

use Ardenexal\FHIRTools\Component\Models\R4B\Resource\PatientResource;
use Ardenexal\FHIRTools\Component\Models\R4B\DataType\HumanName;

$patient = new PatientResource(
    id: 'example-123',
    active: true,
    name: [new HumanName(family: 'Doe', given: ['John'])],
);

// Serialize to JSON
$json = $serializer->serializeToJson($patient);
// {"resourceType":"Patient","id":"example-123","active":true,"name":[{"family":"Doe","given":["John"]}]}

// Deserialize JSON back to a model object
$restored = $serializer->deserializeFromJson($json, PatientResource::class);
echo $restored->id;              // "example-123" (a plain string)
echo $restored->name[0]->family; // "Doe"
```

`serializeToJson(object $fhirObject, array $context = []): string` and `deserializeFromJson(string $jsonData, string $targetClass, array $context = []): object` both accept an optional Symfony serializer context array — see [Context & Options](/serialization/context.md) for validation modes and unknown-element policies.

{% hint style="info" %}
**Primitive typing on round-trip:** simple resource fields such as `id` stay plain PHP scalars, but typed primitive fields (e.g. `HumanName::$family`, `$given[]`) come back as `...\Primitive\StringPrimitive` objects after deserialization. These implement `Stringable`, so `echo` and string interpolation work directly — but a strict comparison needs a cast: `(string) $restored->name[0]->family === 'Doe'`.
{% endhint %}

## Auto-detecting format and resource type

`deserialize(string $data, ?string $targetClass = null, array $context = [])` sniffs JSON vs XML from the payload and resolves the target class from the `resourceType` (JSON) or root element (XML), so you can omit the target class:

```php
<?php

$resource = $serializer->deserialize($json);          // format + class auto-detected
$resource = $serializer->deserialize($json, PatientResource::class); // explicit class
```

Class resolution delegates to the type resolver, so it applies `meta.profile` and the IG type registry when available (see [IG-Aware Serialization](/serialization/ig-aware.md)).

## Error handling

All serialize/deserialize failures are wrapped in `FHIRSerializationException` (which extends the component base `FHIRToolsException`). The underlying decode/denormalize error is preserved as the previous exception.

```php
<?php

use Ardenexal\FHIRTools\Component\Serialization\Exception\FHIRSerializationException;

try {
    $patient = $serializer->deserializeFromJson($maybeInvalidJson, PatientResource::class);
} catch (FHIRSerializationException $e) {
    // Inspect $e->getPrevious() for the underlying cause.
    error_log('FHIR deserialization failed: ' . $e->getMessage());
}
```

`FHIRSerializationException` also exposes `getElementPath()`, `getDetailedMessage()`, and (when debug info was enabled) `getDebugInfo()` / `hasDebugInfo()`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://php-fhir-tools.ardenexal.net/serialization/json.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
