-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Serializer] Empty object + ObjectNormalizer + JSON encoder = empty JSON array #23019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Couldn't a flag/context option be passed to the object normalizer, enabling normalization of empty objects as JSON objects? It would be set to false by default with a deprecation notice saying that it'll be default true in 4.0, and maybe remove it at the end? |
This is still an issue in 4.1, and using an empty Using [
'details' => new \stdClass(),
'prices' => [
['amount' => 12.00, 'symbol' => '$'],
],
] This should encode to |
@chalasr about this comment:
I'm probably missing something ... but the current behaviour looks like a bug to me. Empty PHP objects should generate empty JSON objects, not empty JSON arrays. The last example showed by @simonwelsh explains it well. |
…ys (mcfedr) This PR was merged into the 4.4 branch. Discussion ---------- [Serializer] Encode empty objects as objects, not arrays Allows Normalizers to return a representation of an empty object that the encoder recognizes as such. Often PHP code is relaxed about the difference betweens arrays and objects, and particularly empty arrays are ambiguous. This preserves objects that would otherwise have turned into arrays as objects in the encoding. | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | No | Deprecations? | No | Tests pass? | yes | Fixed tickets | #23019 | License | MIT | Doc PR | I'll do it if/when this might be merged Commits ------- f28e826 [Serializer] Encode empty objects as objects, not arrays
Let us take this small example with Melody:
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 theJsonEncoder
class returns an empty JSON array too:One solution would be to pass an empty
ArrayObject
instance to theJsonEncoder
class: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 anArrayObject
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?
The text was updated successfully, but these errors were encountered: