Skip to content

JsonSerializableNormalizer does not use the ATTRIBUTES option #45995

Closed
@linaori

Description

@linaori

Symfony version(s) affected

4.4

Description

The AbstractNormalizer::ATTRIBUTES option does nothing for the JsonSerializableNormalizer, and I suspect that other options are unused as well.

My work-around is something like this:

foreach ($rows as &$row) {
    if ($row instanceof JsonSerializable) {
        $row = $row->jsonSerialize();
    }

    if (is_array($row)) {
        // mimic AbstractNormalizer::ATTRIBUTES as json does not support this
        $row = array_filter($row, static fn (string $key) => isset($fields[$key]), ARRAY_FILTER_USE_KEY);
    }
}

How to reproduce

$obj = new class () implements JsonSerializable {
    private string $field1 = 'value 1';
    private string $field2 = 'value 1';
    public function jsonSerialize()
    {
        return ['field1' => 'value 1', 'field2' => 'value 2'];
    }
};
$serializer = new Serializer([new PropertyNormalizer()], [new JsonEncoder()]);
dump($serializer->serialize($obj, 'json', ['attributes' => ['field1']]));
// "{"field1":"value 1"}"

$serializer = new Serializer([new JsonSerializableNormalizer()], [new JsonEncoder()]);
dump($serializer->serialize($obj, 'json', ['attributes' => ['field1']]));
// "{"field1":"value 1","field2":"value 2"}"

Possible Solution

As plain arrays also suffer from this issue, I think it's best to have this filter be applied regardless of normalizer. Perhaps it could normalize first, then once it has an array of data, filter the keys, and then pass that to the encoder?

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions