M
M
Maxim Barulin2014-12-19 12:11:57
symfony
Maxim Barulin, 2014-12-19 12:11:57

Why does JMS Serializer ignore entity-mapping files during manual serialization?

Good day,% habrauser%!
I use symphony for rest with the corresponding standard set of bundles. When simply returning an object as a result of the method execution, serialization proceeds correctly according to the mapping. But here it was necessary to serialize the entity by hand and faced with the fact that the mapping is completely ignored. And everything would be fine, it would be possible to set everything up with annotations, but my user class is inherited from Fosovsky, and you can’t add anything there. How to make mapping files work during manual serialization?
config:

jms_serializer:
    metadata:
        debug: %kernel.debug%
        file_cache:
            dir: "%kernel.cache_dir%/serializer"
        auto_detection: true
        directories:
            FOSUserBundle:
                namespace_prefix: FOS\UserBundle
                path: "@ApiRestRestBundle/Resources/config/serializer/fosuser"

Mapping files are located in the Resources/config/serializer directory
Code for serialization:
use JMS\Serializer\SerializerBuilder;

$serializer = SerializerBuilder::create()->build();
$ser_user = $serializer->serialize($user, 'json');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Benkovsky, 2014-12-19
@Slavenin999

See, Symfony2 has such a thing as Dependency Injection . What's the point? The fact is that you configure all the services that you need in the config files, the config files are parsed by Symfony, and in the code you use cat services. Now let's look at your code:

jms_serializer: 
....

you set up a serializer that will get into DI
use JMS\Serializer\SerializerBuilder;

$serializer = SerializerBuilder::create()->build();
$ser_user = $serializer->serialize($user, 'json');

And here you create a NEW serializer instance and use it. This SerializerBuilder is a factory, it returns a NEW serializer. It doesn't know anything about your configs.
Find out how to inject an already configured serializer into your code. (if your controller code is $serializer = $this->get('jms_serializer'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question