Serialize empty object as empty object instead of empty array with Symfony serializer

Serialize empty object as empty object instead of empty array with Symfony serializer

The Symfony serializer now for long had the logic that any object without values will be serialized to an empty array. The problem here is for the frontend when they expect an object. For example they might have a Typescript interface like the following:

interface User {
  firstName: string;
  lastName: string;
  token: Token;
}

interface Token {
  hash?: string;
}

In this example the hash of the token is optional. When you serialize it and use the ObjectNormalizer::SKIP_NULL_VALUES flag, then the response will be:

{
  "firstName": "Max",
  "lastName": "Mustermann",
  "token": []
}

There are three ways to solve this:

  • Have a special api layer which converts this for every endpoint where this might happen
  • Add at least one required property like an id to the object (this way it will always be an object)
  • Use a new flag introduced in version 4.4 of the serializer

This is the way no possible. Simply add the following flag to your serializer:

ObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,

Like this:

$serializer->serialize($data, JsonEncoder::FORMAT, [
    ObjectNormalizer::SKIP_NULL_VALUES => true,
    ObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
]);

I moved the whole serializer part into a separate service and serialize everything that way.