Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 62 ยท APIs

The Serializer Component

Learn how the Symfony Serializer turns objects into JSON and back with normalizers and encoders, serialization groups and attributes, with runnable stand-ins.

PHP objects and JSON text are different things. Your code wants a Book with typed properties; the network wants a string. Converting between the two by hand means writing toArray() and fromArray() methods for every class, and keeping them in sync as the classes change. The Serializer component does that job generically.

It splits the work in two steps. A normalizer converts an object to a plain array (and back). An encoder converts that array to a string format such as JSON or XML (and back). Once you see the two steps, most of the component's options make sense. This lesson explains both, shows groups and attributes for controlling the output, and rebuilds the idea in runnable plain PHP. It builds on building JSON APIs.

Two steps: normalize, then encode

flowchart LR
    O["Book object"] -->|normalize| A["Array<br/>(scalars and arrays only)"]
    A -->|encode| S["JSON string"]
    S -->|decode| A2["Array"]
    A2 -->|denormalize| O2["Book object"]

Serializing is normalize plus encode; deserializing is decode plus denormalize.

The SerializerInterface hides this behind two methods:

PHP
// src/Controller/BookController.php (real Symfony, read-only)
use Symfony\Component\Serializer\SerializerInterface;

$json = $serializer->serialize($book, 'json');
$book = $serializer->deserialize($json, Book::class, 'json');

The second argument is the format. Symfony ships encoders for json, xml, csv and yaml, so switching format is a change of one string.

With the Symfony Flex setup, composer require symfony/serializer-pack installs the component with its usual helpers. The serializer is then an autowireable service, and $this->json($data) in an AbstractController uses it automatically.

What the default normalizers do

The ObjectNormalizer reads an object through its public API: public properties, getters such as getTitle(), boolean getters such as isPublished() and hasX() methods. Each becomes a key (title, published). For deserializing it uses the constructor arguments and setters, and it respects declared types, so the string "7" becomes the integer 7 for an int property.

Other normalizers handle special values. There is one for DateTimeInterface (it produces an ISO 8601 string by default), one for backed enums (their value), one for Uuid objects, and a few more. The serializer asks each normalizer, in priority order, "can you handle this value?" and uses the first that says yes.

The default ObjectNormalizer exposes everything it can read. Serializing a User entity without limits can leak a password hash, an apiToken or an internal flag. Always restrict what leaves your application, using groups, ignores or a dedicated output DTO.

Controlling output: attributes and groups

Symfony reads serializer attributes from the class itself. The ones you will use daily:

PHP
// src/Entity/Book.php (real Symfony, read-only)
namespace App\Entity;

use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\Ignore;
use Symfony\Component\Serializer\Attribute\SerializedName;

class Book
{
    #[Groups(['book:read', 'book:list'])]
    private int $id;

    #[Groups(['book:read', 'book:list', 'book:write'])]
    private string $title;

    #[Groups(['book:read', 'book:write'])]
    private string $summary = '';

    #[Groups(['book:read'])]
    #[SerializedName('published_at')]
    private ?\DateTimeImmutable $publishedAt = null;

    #[Ignore]
    private string $internalNotes = '';

    // getters and setters ...
}
  • #[Groups([...])] tags a property with one or more group names. When you serialize with ['groups' => ['book:list']], only properties in that group appear. This is how one entity serves a short list view and a full detail view.
  • #[SerializedName('published_at')] renames the key without renaming the PHP property.
  • #[Ignore] removes a property from the output completely.

You pass the active groups in the context:

PHP
// real Symfony, read-only
$json = $serializer->serialize($books, 'json', ['groups' => ['book:list']]);

A naming convention helps for write groups too: book:read for what clients may see, book:write for what they may send. Deserializing with ['groups' => ['book:write']] ignores any other fields in the incoming JSON, which protects properties such as id from being set by the client.

To convert publishedAt into published_at for every property at once, configure the CamelCaseToSnakeCaseNameConverter instead of renaming one by one. It is registered as a name converter in config/packages/framework.yaml under framework.serializer.name_converter.

Useful context options

The context is an array of options passed with each call. A few that come up constantly:

  • AbstractNormalizer::IGNORED_ATTRIBUTES: a list of properties to leave out.
  • AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER: what to do when Author points to Book and Book back to Author. Without handling, serializing such a graph throws an exception. Better still, cut the cycle with groups.
  • AbstractNormalizer::OBJECT_TO_POPULATE: update an existing object instead of creating a new one, which is how a PATCH endpoint can be built.
  • AbstractObjectNormalizer::SKIP_NULL_VALUES: omit keys whose value is null.
  • AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES set to false: reject unknown fields in incoming data instead of silently dropping them.
  • DateTimeNormalizer::FORMAT_KEY: the date format for output.

Deserialization and its errors

Turning JSON into an object can fail in several ways: invalid JSON (NotEncodableValueException), a missing constructor argument or a wrong type (NotNormalizableValueException, or a PartialDenormalizationException that collects all type problems when you enable COLLECT_DENORMALIZATION_ERRORS). That last option is what powers the nice field-by-field error messages of #[MapRequestPayload], which is built on top of this component.

Deserialization checks types, not rules. A title of "" is a perfectly valid string. Rules such as "not blank" belong to the validator, which you run on the object after deserializing.

Building the idea in plain PHP

Here is a stand-in that makes the two steps visible. A tiny normalizer reads an object with reflection, honours a group attribute, formats dates and renames keys; a tiny encoder turns arrays into JSON. It is not Symfony's code, but it follows the same idea.

PHP Normalizing objects with groups (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The same object gives three different JSON documents depending on the groups, and internalNotes never appears in any of them because of #[Ignore]. With no groups the stand-in includes every non-ignored property, as Symfony does.

The other direction: denormalizing

Denormalizing builds an object from an array: read the constructor, match each parameter by name, convert the value to the declared type, and complain about anything missing. This example also shows the "extra attributes" option.

PHP Denormalizing arrays into objects (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The string "7" becomes the integer 7, a missing optional field falls back to its default, and a missing required one fails with a clear message. The last case is the safety option: with extra attributes forbidden, a hostile isAdmin field is rejected rather than ignored.

Custom normalizers and when to avoid them

When an object does not map neatly to JSON (for example a Money value object that should appear as "12.50 EUR"), write your own normalizer: a class implementing NormalizerInterface and DenormalizerInterface with supportsNormalization(), normalize() and their counterparts. With autoconfiguration, it is registered automatically through the serializer.normalizer tag (see service tags).

Reach for a custom normalizer sparingly. The simplest API code often skips entity serialization entirely: build a small output DTO (or an array) in the controller, and serialize that. You get an explicit public contract that does not change when your database columns do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a normalizer and an encoder?

    Serializing is normalize (object to array) then encode (array to string). Deserializing reverses both steps.
  2. 2. How do serialization groups help an API?

    Properties are tagged with group names and the active groups come from the context, so each endpoint exposes only what it needs.
  3. 3. A client sends JSON containing a field you never intended to accept. Which context option makes the serializer reject it?

    With extra attributes disallowed, unknown keys cause an error instead of being silently dropped.
  4. 4. A deserialized title is an empty string. Who is responsible for rejecting it?

    The serializer checks types, not business rules. Constraints such as NotBlank belong to the Validator component.

Summary

  • Serializing is normalize (object to array) plus encode (array to JSON, XML, CSV or YAML); deserializing is the reverse.
  • The default ObjectNormalizer exposes everything readable, so restrict output with #[Groups], #[Ignore] or an output DTO.
  • #[SerializedName], name converters and context options control keys, dates, nulls and unknown fields.
  • Deserialization checks types and shapes; the validator checks rules.
  • Custom normalizers handle special value objects, but a small output DTO is often simpler.
  • The runnable examples are stand-ins; the Symfony code is real and read-only here.

Next up: API Platform Overview.