jmack
jmack

Reputation: 189

Serializing and Deserializing in Symfony

I am serializing entities with the Symfony bundle "symfony/serializer".

I am able to encode my entity into json with no problems, however I am having problems deserializing it and bringing it back into its original form. The error I am receiving is;

Could not denormalize object of type AppBundle:Entity, no supporting normalizer found.

DefaultController.php

    //Create Entity to Serialize
    $entity = new Entity();
    $entity->setId(1);
    $entity->setName('john');

    //create serializer to serialize entity
    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new ObjectNormalizer());
    $serializer = new Serializer($normalizers, $encoders);
    $jsonContent = $serializer->serialize($entity, 'json');

    var_dump($jsonContent); // returns string '{"id":1,"name":"john"}' (length=22)  << GOOD!


    //Deserialize entity
    $person = $serializer->deserialize($jsonContent, 'AppBundle:Entity', 'json');
    //<ERROR HERE>//

    var_dump($person); 

Entity.php

namespace AppBundle\Entity;

class Entity {

private $id;

private $name;

public function getId()
{
    return $this->id;
}

public function setId($id)
{
    $this->id = $id;
}

public function getName()
{
    return $this->name;
}

public function setName($name)
{
    $this->name = $name;
}

}

Not too sure what I am missing, any help greatly appreciated.

Upvotes: 2

Views: 10096

Answers (3)

voodoo
voodoo

Reputation: 54

The deserializer Type should be the namespace including the entity name separated by two backslashes :

$person = $serializer->deserialize($jsonContent, 'AppBundle\\Entity', 'json');

Upvotes: 0

Yann Eugon&#233;
Yann Eugon&#233;

Reputation: 1351

Symfony's serializer component is really interesting (I do not use JMS Serializer anymore...)

The only thing you have to configure is : the normalizers

Normalizers are simple services registered with a tag.

There is some built-in classes like :

  • Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer : use getter and setter to (de)normalize
  • Symfony\Component\Serializer\Normalizer\PropertyNormalizer : use reflection to (de)normalize
  • Symfony\Component\Serializer\Normalizer\CustomNormalizer : provide you a way to define progamatically the behavior of you normalization

For your case, just register this service :

<service id="app.normalizer.get_set" class="Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer">
    <tag name="serializer.normalizer" priority="0" />
</service>

You are all set

Upvotes: 3

D_R
D_R

Reputation: 4972

deserialize() should get the namespace of the entity so you need to change AppBundle:Entity to AppBundle\Entity.

$person = $serializer->deserialize($jsonContent, 'AppBundle\Entity', 'json');

Upvotes: 1

Related Questions