JMSSerializerBundle: specify group per attribute
Asked Answered
D

1

1

I'm using Symfony2 and JMSSerializerBundle to build an API. The system that JMSSerializer provides to set different ways of serializing objects using groups is quite useful, however, I'm missing a way to specify which group do you want to serialize in every parameter. Example:

I have an article that is related to a user (author). Articles as well as users can be serialized as "list" or as "details", however, I want the users to be serialized as "list" always that they are retrieved from the article (because "details" group is reserved to be used to fetch the user and just the user). The problem is that if I set the serializer as "details", then the author is also serialized as "details".

In my mind, the code should be something like:

/**
 * @var SCA\APIBundle\Entity\User
 * @Groups({"list" => "list", "details" => "list"})
 */
private $author;

where the key of the array indicates the way the parent should be serialized, and the value indicates the way the child should be serialized.

Any clue how can I achieve this?

Debauch answered 2/12, 2012 at 0:50 Comment(0)
R
0

It should not be done on the composed object but on the composition.

In your case, I suppose you have something like that:

class Article
{
    /**
     * @var User
     * @Groups({"list", "details"})
     */
    private $author;
}


class User
{
    private $firstName;
    private $lastName;
}

So if you want to expose the firstName property when serializing the composed object, you need to define the same group in the User object.

It becomes:

class Article
{
    /**
     * @var User
     * @Groups({"list", "details"})
     */
    private $author;
}


class User
{
    /*
     * @Groups({"list"})
     */
    private $firstName;
    private $lastName;
}

If you need more control, you may define more explicit groups, like "article-list", "user-firstname", "user-list-minimal", etc.

It is up to you to decide the best strategy to adopt.

Rufous answered 12/12, 2012 at 11:13 Comment(2)
Yes, that's the solution I was going to use, but I supposed that there should be some other way of accomplish this, as this way is a little bit difficult to maintain if you have a big amount of classes.Growl
@aperezroca, I agree that may be a bit counter intuitive, but I guess it is due to some limitation on how the exclusion strategy works (reflection)Acne

© 2022 - 2024 — McMap. All rights reserved.