Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Serializer] Empty object + ObjectNormalizer + JSON encoder = empty JSON array #23019

Copy link
Copy link
Closed
@meyerbaptiste

Description

@meyerbaptiste
Issue body actions
Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no
Symfony version >= 2.7

Let us take this small example with Melody:

<?php
<<<CONFIG
packages:
    - "symfony/serializer: ^3.3"
    - "symfony/property-access: ^3.3"
CONFIG;

$encoders = [new Symfony\Component\Serializer\Encoder\JsonEncoder()];
$normalizers = [new Symfony\Component\Serializer\Normalizer\ObjectNormalizer()];
$serializer = new Symfony\Component\Serializer\Serializer($normalizers, $encoders);

var_dump($serializer->serialize(new class {}, 'json')); // string(2) "[]"

As you can see the result is an empty array ([]) instead of an empty object ({}). IMO this behavior is an important problem and it should be considered as a bug.

This problem comes from the ObjectNormalizer class which returns an empty array so the JsonEncoder class returns an empty JSON array too:

var_dump(json_encode([])); // string(2) "[]"

One solution would be to pass an empty ArrayObject instance to the JsonEncoder class:

var_dump(json_encode(\new ArrayObject)); // string(2) "{}"

To arrive to this result, we have to change the contract of the NormalizerInterface::normalize() method to return an iterable (or a scalable as currently) instead of an array.

In addition, as discussed with @dunglas, this change would allow us to use generators with normalizers.

Then we would be able to adapt the ObjectNormalizer class to deal with an ArrayObject instance instead of an array. As you can imagine, it's a huge BC break but I don't have a better solution to fix this issue...

WDYT?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.