Question

Basically I want to deserialize json to user object. Like this

$serializer = $this->get('jms_serializer');

$data = $serializer->deserialize($this->get('request')->getContent(),
                                 'My\FooBundle\Entity\User', 'json');

The request data passed to deserializer:

{"id":2,"username":"...@gmail.com","username_canonical":"...@gmail.com", ... }

Thrown error:

request.CRITICAL: Uncaught PHP Exception JMS\Serializer\Exception\RuntimeException: "You must define a type for FOS\UserBundle\Model\User::$username." at ...\vendor\jms\serializer\src\JMS\Serializer\GenericDeserializationVisitor.php line 170 [] []

I use sf 2.3. Is there anything that has to be setup for deserialization of fos user class? Any idea why I get this message and how to fix it?

Was it helpful?

Solution

Hello I just had the same problem today and finally found how to deal with this non issue,

for each properties in an object you want to deserialize, the bundle wants to know which type you expect to have after the conversion. So you must use the annotation\type provided by the bundle in your Entity class and annote each properties: http://jmsyst.com/libs/serializer/master/reference/annotations#type

BE CAREFUL: Paste is evil! the use statement in the reference example is use JMS\Serializer\Annotation\Type; but should be the real path to the serializer use JMS\SerializerBundle\Annotation\Type;

an exemple from my code :

    use JMS\SerializerBundle\Annotation\Type;
    /**
    * @ORM\Entity
    * @ORM\Table(name="ecro_form")
    */
     class Form {

     /**
     * @ORM\ManyToOne(targetEntity="eCRO\Bundle\UserBundle\Entity\User", inversedBy="forms")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * @Type("eCRO\Bundle\UserBundle\Entity\User")
     */
     protected $user; // inherits from FOSUser

Use annotations on the FOSUser abstract class (location: vendor\FOS\UserBundle\Model\User.php) so that the serializer know how to do its work.

hope it will help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top