Skip to content

Navigation Menu

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] Add a annotation (or something) to serialize empty collection as an object and not an array #38192

Copy link
Copy link
Closed
@lyrixx

Description

@lyrixx
Issue body actions

Description

I faced a stupid issue this morning. I have an API with a new property called metadata. It's an array in PHP, and it's stored as JSON in our DB. We can store whatever we want in it.
Fore example: {"hidePinCrawlExplanation":true}.

When the property is empty, its value is [] (in PHP or JSON).

But, in JS, I have an issue. If I write the following code:

user.metadata.hidePinCrawlExplanation = true;

I end up with the following "shape":
image

As you can see, this does not make any sens:

  • it's an array
  • but is has key

So when I serialized it back to JSON I got: metadata: [] 🤦🏼

Summary in one image:

image

(Thanks JS :trollface: )

So an idea (from @pyrech): Add an annotation to the property to tell the serializer to serialize it as {} and not [] when the collection is empty.

Example

    /**
     * @ORM\Column(type="json_array")
     * @Groups({"user:read", "user:edit_metadata"})
     * @SerializeEmptyCollectionAsObject()
     */
    private array $metadata;

/cc @dunglas

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFCRFC = Request For Comments (proposals about features that you want to be discussed)RFC = Request For Comments (proposals about features that you want to be discussed)Serializer

    Type

    No type

    Projects

    No projects

    Milestone

    No 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.