API Platform: normalization context ignored in nested objects

Viewed 270

I have an API resource entity like this:

/**
 * @ApiResource(
 *     collectionOperations={},
 *     itemOperations={"get"},
 *     normalizationContext={"groups"={"read"}},
 * )
 */
class A
{
    /**
     * @var array<B>
     * @Groups("read")
     */
    private array $b;

    // ...
}

The @Groups annotation for properties works, I only get those with @Groups("read").

But I have nested objects like this:

class B
{
    /**
     * @var array<C>
     * @Groups("read")
     */
    private array $c;

    // ...
}

class C
{

    /**
     * @Groups("read")
     */
    private string $foo;

    private string $bar;

    // ...
}

In B, the @Groups annotation is still respected, but in C I get all properties, completely ignoring annotations.

Expected output like:

{
  "b": [
    {
      "c": [
        {
          "foo": "This should be public"
        }
      ]
    }
  ]
}

Got output like:

{
  "b": [
    {
      "c": [
        {
          "foo": "This should be public"
          "bar": "This should be private"
        }
      ]
    }
  ]
}

What do I need to do to make this work?

(if it matters, neither B nor C is an @ApiResource, but C is a Doctrine @Entity. I use a custom data provider for A)

1 Answers

I found it... C implemented JsonSerializable, for other reasons, and the JSON represenation from jsonSerialize() contained foo and bar.

API Platform apparently makes use of that if it exists. Something learned!

Related