solarc
solarc

Reputation: 5738

Symfony Serializer doesn't deserialize into objects in different namespace: 'no supporting normalizer found'

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:

Thanks for the help

Upvotes: 3

Views: 2152

Answers (1)

yceruto
yceruto

Reputation: 9575

The error occurs because Foo class doesn't exists in this context, you've probably forgotten to include this file Somewhere/Foo.php to autoload.

In your sample this should work!

<?php // file tests/Test.php

namespace tests;

include 'Somewhere/Foo.php';

//...

Some editors as PHPStorm are able to auto-import the Foo class if it's in the same directory without show any error.

Upvotes: 3

Related Questions