I'm trying to deserialize json into an object using the packages symfony/serializer and symfony/property-access through composer. It works when the class I'm deserializing into is in the same file, but not when it's somewhere else (not even a different file in the same namespace). I have the following code:
<?php // Somewhere/Foo.php
namespace Somewhere;
class Foo
{
private $foo;
public function getFoo() { return $this->foo; }
public function setFoo($foo) { $this->foo = $foo; }
}
And:
<?php // file tests/Test.php
namespace tests;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Somewhere\Foo;
class Foo2
{
private $foo;
public function getFoo() { return $this->foo; }
public function setFoo($foo) { $this->foo = $foo; }
}
class Test extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer(), new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$payload = '{"foo": {"bar": "baz"}}';
$obj = $serializer->deserialize($payload, Foo::class, 'json');
$this->assertInstanceOf(Foo::class, $obj);
}
public function testFoo2()
{
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer(), new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$payload = '{"foo": {"bar": "baz"}}';
$obj = $serializer->deserialize($payload, Foo2::class, 'json');
$this->assertInstanceOf(Foo2::class, $obj);
}
}
The test using the local class (Foo2) works fine, but the one using the class in a different namespace (\Somewhere\Foo) shows me this error:
Symfony\Component\Serializer\Exception\UnexpectedValueException: Could not denormalize object of type Somewhere\Foo, no supporting normalizer found.
I've tried using \Somewhere\Foo::class, 'Foo' and '\Somewhere\Foo' instead of Foo::class too without any luck.
Similar Questions:
- Serializing and Deserializing in Symfony marks one answer which uses strings as correct but not really, if you read the comments you'll see it didn't really solved the question.
- Could not denormalize object of type, no supporting normalizer found. Symfony 2.8 In the comments the OP says using
ClassName::classworked, but this doesn't work for me. - Problems try encode entity to json The answer was to stop using
symfony/serializerand usejms/serializerinstead. Is it really not possible with Symfony's serializer?
Thanks for the help