# Serializer

## Serializer

## Serializer - deserialize update object

*The Serializer component is meant to be used to turn objects into a specific format (XML, JSON, YAML, ...) and the other way around.*

Normalizers (object < = > array)

Encoders (format(json, xml, csv, yaml…) < = > array)

**Core Components**:

* **Normalizers**: Transform objects to and from arrays. Different normalizers are available for handling various types of objects.
* **Encoders**: Convert arrays into specific formats (like JSON, XML, CSV) and decode these formats back into arrays.
* **Context**: Provides additional settings or parameters to influence the serialization and deserialization processes.
* Serialize (object ⇒ format)

```php
use App\Model\Person;

$person = new Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsperson(false);

$jsonContent = $serializer->serialize($person, 'json');

// $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}
```

* deserialize (format ⇒ object)

```php
use App\Model\Person;

$data = <<<EOF
<person>
    <name>foo</name>
    <age>99</age>
    <sportsperson>false</sportsperson>
</person>
EOF;

$person = $serializer->deserialize($data, Person::class, 'xml');
```

* deserialize can be used to update the object to

```php
// ...
$person = new Person();
$person->setName('bar');
$person->setAge(99);
$person->setSportsperson(true);

$data = <<<EOF
<person>
    <name>foo</name>
    <age>69</age>
</person>
EOF;

$serializer->deserialize
							(
								$data, 
							  Person::class, 
								'xml', 
								[AbstractNormalizer::OBJECT_TO_POPULATE => $person]
);
// $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true)
```

This is a common need when working with an ORM.

The `AbstractNormalizer::OBJECT_TO_POPULATE` is only used for the top level object

If that object is the root of a tree structure, all child elements that exist in the normalized data will be re-created with new instances.

When the `AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE` option is set to true, existing children of the root `OBJECT_TO_POPULATE` are updated from the normalized data, instead of the denormalizer re-creating them. Note that `DEEP_OBJECT_TO_POPULATE` only works for single child objects, but not for arrays of objects. Those will still be replaced when present in the normalized data.

#### Context

Context refers to additional settings to pass to the serializer/deserializer

You can pass the context as follows:

```php
$serializer->deserialize($someJson, Something::class, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);
```

or

```php
# config/packages/framework.yaml
framework:
    # ...
    serializer:
        default_context:
            enable_max_depth: true
            yaml_indentation: 2
```

or

```php
#[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
public \DateTimeInterface $createdAt;
```

#### Features

* attributes groups

to normalize/denormalize different attributes

```php
class MyObj
{
    #[Groups(['group1', 'group2'])]
    public string $foo;
```

* selecting specific attributes

```php
$data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
```

* ignoring attributes

```php
$serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"}
```

* Converting property names: custom, camelCase to snake\_case
* booleans: it works for has, get and can (App\Model\Person::isSportsperson())
* callbacks: When serializing, you can set a callback to format a specific object property.

#### Normalizer

Normalizers in Symfony's Serializer are responsible for converting data between object and array (or scalar values) formats.

Object < = > array

object, getSet, property, datetime…

Always make sure to load the `DateTimeNormalizer` when serializing the `DateTime` or `DateTimeImmutable` classes to avoid excessive memory usage and exposing internal details.

#### Encoders

Encoders are components that handle the final stage of serialization — converting normalized data (arrays or scalar values) into a specific format (like JSON or XML) and vice versa.

array < = > formats

json, xml, csv, yaml

**Circular Reference Handling**:

* The Serializer can handle circular references to prevent infinite loops during serialization, which is crucial in object graphs with bidirectional relationships.


---

# Agent Instructions: 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://senens-organization.gitbook.io/senenhermida.docs/symfony/serializer.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.
