I'm trying to serialize and deserialize between json and doctrine entity but keep getting this error
"Could not denormalize object of type AppBundle/Person, no supporting normalizer found. "
My entity class
<?php
namespace AppBundle\Entity;
class Person
{
private $age;
private $name;
// Getters
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
// Setters
public function setName($name)
{
$this->name = $name;
}
public function setAge($age)
{
$this->age = $age;
}
}
My controller
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Person;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
class RawGrnController extends Controller
{
public function newAction(Request $request)
{
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer(),new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$data =$data = <<<EOF
<person>
<name>foo</name>
<age>99</age>
</person>
EOF;
$person = $serializer->deserialize($data, 'AppBundle\Person', 'xml');
$reaponse = new Response($person);
return $reaponse;
}
}
I got this code from the official Symfony documentation Here.I have tried to use this in my real project and got the above error then, I tried the example on the documentation but still getting the same error.
Things I've tried so far
- Serialize an object to json/xml and tried to deserialize it again
- Decode json/xml to an array and then denormalize to an object(decode is successful but denormalizing gives the same error)
- Tried to use serializer as a service as described in Here
I have no clue what I'm missing to get the normalizer to work. Objects in my project are far more complex but I'm getting bit suspicious as the example in documentation gives the same error. Any help is highly appreciated.
$person = $serializer->deserialize($data, 'AppBundle\Entity\Person', 'xml');
? Note the namespace$person = $serializer->deserialize($data, Person::class, 'xml');
This did the trick for me but I don't know how to explain this behavior. Can anyone explain?