06.
Serialization Event Subscriber
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
11 Comments
Hi,
I'm trying to do the pagination with knpPaginationBundle. The paginated object has also properties like links etc. But when I serialize the objectwith the Symfony serializer, a json is created which only contains the items. I've tried different things, but I don't really understand where the problem is with serializing. By default it works with the jms serializer and the json result is as expected.
My question now is, where exactly does the problem occur and how can I customize the process, so that symfony serialize the object correctly? I would really like to serialize without jms
Hey Skander B.!
Excellent question :). First, when you serialize an object with the Symfony serializer, "basically" the fields that will be included are all the fields that have a getter method. If I remember correctly, with the paginator, you're dealing with a
SlidingPaginationinstance (https://symfonycasts.com/screencast/api-platform) which extendsAbstractPaginationhttps://github.com/KnpLabs/knp-components/blob/master/src/Knp/Component/Pager/Pagination/AbstractPagination.php. As you can see - if you search forpublic function get, you'll find methods for the current page, the current items, total item count and a few others - but not links. My guess is that the fields you ARE seeing are these fields.To improve this, you have a few options:
1) Create your own class that has all the "getter" methods you want for the fields and manually take the
SlidingPaginationobject and populate your object with its data. Then serializer your object.2) Create a custom serializer "normalizer". This is basically a class that will take complete control over the normalization process of just the
SlidingPaginationclass and will give you control over including whatever fields you want. For example, here is a "core normalizer" whose job is to make sure thatConstraintViolationListobjects (that's what Symfony's validator returns, and it includes validation errors) is normalized into a useful structure: https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.phpCheers!
Thank you very much for your quick and detailed answer! :D I also had the idea to write my own normalizer for it.
And you are definitely right, I get a <u>SlidingPagination</u> object. I also suspected that "links" had no public getter. However, I really only get the current items, so by the <u><i>getItems()</i></u> method in <u>AbstractPagination</u> class, right?
All other getters are ignored. This includes for example <i><u>getTotalItemCount()</u></i>. I have noticed that in SlidingPagination the <i><u>getPaginationData()</u></i> method exposes all data that I am missing:
...
`
$viewData = [
$viewData = array_merge($viewData, $this->paginatorOptions, $this->customParameters);
`
I just wonder why of all methods only <i><u>getItems()</u></i> is captured by the symfony normalizer and other getters of <u>AbstractPagination</u> are not? Or have I looked at the wrong classes for this? It is generally difficult for me to debug during the serialization process. Do you have any tips?
Just for completion I'm attaching you an example json of a serialized <u>SlidingPagination</u> object:
`[
]`
Hey Skander B.!
Hmm. Indeed, this looks weird to me - I would expect all the getters to be called by default. But, it's even stranger than that. If this follows the normal normalization rules, then the "getItems()" method would cause an
itemskey to be added in the JSON. But in your JSON example, all the results are at the root level, not under an "items" key. So, that's a mystery :).It makes me wonder if the project already has a custom normalizer for this class. I could totally be wrong.. but I don't see any "core" normalizer for that pagination class that comes with KnpPaginator... so I don't think it's being added by that bundle. Your question on how to debug is an excellent one :). Unfortunately, there isn't a spot on the web debug toolbar/profiler for the serializer... which would be super handy. But, you can at least see what normalizers exist on your project by running:
I would check there to see if any of those classes might be responsible.
... Wait! I think I just figured it out! AbstractPagination implements
Iterator. If there is no normalizer for a specific class that implements Iterator, then the Serializer automatically "loops over" the object and normalizes each item (https://github.com/symfony/symfony/blob/46e94d94255ea785f5b138312e6f664da2ccfbe9/src/Symfony/Component/Serializer/Serializer.php#L159). THAT is what explains the result :).So, creating a custom normalizer is still a great option... and we can now explain what's going on ;).
Cheers!
Hi, Is `@VirtualProperty` outdated? Can't find anything about that in documentation.
Hi Pawel,
AFAIK, it isn't. Probably you don't see it in the docs for bundle, try to look at docs for serializer package itself:
https://jmsyst.com/libs/ser...
Cheers!
thanks, (sorry, somehow I forgot it's not about Symfony The Serializer Component, and I searched there)
Hi,
I don't know if this is the tutorial to ask this, but I have the following question.
I have an Entity JobOffer. This Entity contains an image from the Sonata MediaBundle like this:
Entity JobOffer
...
/**
* @Serializer\Expose()
* @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"all"})
*/
private $image;
...
When I get the response I can see the property like this:
Response from GET /api/joboffer/1
...
["image"]=>
object(stdClass)#6405 (0) {
}
...
Unfortunately I'm not able to get the details like the name or reference of the Image.
What do I have to change to get this information?
Hey Tim,
Hm, could you tell us to what exactly are you trying to serialize JobOffer? Are you trying to serialize JobOffer as JSON? And your response looks like a var_dump()' output. What code gives you this output? And how did you expose Media entity properties? As I understand this entity comes from third-party bundle, so you can't add annotation to it, right? Do you use some YAML/XML configuration for it?
Cheers!
Hey Victor,
I'm trying to serialize my JobOffer Entity just like Programmer in the tutorial. This is in my showAction in my jobOfferController.php:
The createApiResponse lives in my BaseController.php like in the tutorial:
For the image I use the Sonata Media Bundle (I have the same issue with the Sonata Classification Bundle)
And I use a media.yml to configure it (config.yml imports: - { resource: Sonata/media.yml }) sonata_madia: ...
Full configuration:
https://sonata-project.org/bundles/media/3-x/doc/reference/advanced_configuration.html
I hope this makes things more clear.
Hey Tim V.!
Ok, I might have some info for you, though I have almost zero experience with the Sonata libraries :).
1) SonataMediaBundle itself comes with some serialization config that tells JMSSerializer how to serialize the Media entity: https://github.com/sonata-project/SonataMediaBundle/blob/3.x/src/Resources/config/serializer/Model.Media.xml. That's great news! However, notice that every field is assigned a few groups like "sonata_api_read,sonata_api_write,sonata_search" for the "name" field. When you serialize, I believe you will need to include one of these groups so that these fields setup. I would add a new, optional 2nd
$groupsargument to the serialize() so that you can pass in a custom group (you'll also need to add a 3rd argument to createApiResponse() with this same argument).2) But, there is one other thing that is troubling me. You said:
>Response from GET /api/joboffer/1
>...
>["image"]=>
>object(stdClass)#6405 (0) {
>}
>...
The weird part about this is the stdClass object. The image property should be a Media object - not an stdClass. I would double-check (by var_dump($jobOffer)) to make sure that this property is what you expect. I also found it strange that it printed this string "object(stdClass)#6405 (0) {" in ISON. That's not JSON - that's the result of var_dump(). What does the full JSON response look like? I think something else is not quite right...
Cheers!
"Houston: no signs of life"
Start the conversation!