Symfony denormalization: Recursive Denormalization not working

Viewed 734

I'am trying to desirialize the following Json structure into a Profile object

{
    "label": "lorem label",
    "info": {
        "name": "lorem name",
        "title": "lorem title"
    }
}

I have a class Profile

namespace App\Document;

class profile
{
   /**
    * @var string
    */
   protected $label;

   /**
    * @var Info
    */
   protected $info;

// getters and setters
}

and a class Info

namespace App\Document;

class Info
{
    /**
     * @var string
     */
    protected name;

    /**
     * @var string
     */
    protected title;

    // getters & setters
}

my controller's code is the following

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use App\Document;

public function addProfile(Request $request, DocumentManager $dm, $profile_id)
{
    $phpDocNormalizer = new ObjectNormalizer(null, null, null, new PhpDocExtractor());
    $reflectionNormalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
    $serializer = new Serializer([$phpDocNormalizer, $reflectionNormalizer], [new JsonEncoder()]);

    $profile = $serializer->deserialize($request->getContent(), Profile::class, 'json');

    return new JsonResponse(Response::HTTP_CREATED);
}

As the symfony docs says, i have the phpDocExtractor set and working, and the doc annotations are set too, the PropertyInfo Component is installed too. But i keep getting this NotNormalizableValueException:

The type of the "info" attribute for class "App\Document\Profile" must be one of "App\Document\Info" ("array" given).

I've been stuck with this one for a while now, any help is much appreciated.

1 Answers
public function addProfile(Request $request, DocumentManager $dm, $profile_id)
{
    $extractors = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
    $normalizer = new ObjectNormalizer(null, null, null, $extractors);
    $serializer = new Serializer([$normalizer], [new JsonEncoder()]);
    $profile = $serializer->deserialize($request->getContent(), Profile::class, 'json');

    return new JsonResponse(Response::HTTP_CREATED);
}

You can find a more detailed example here : https://symfony.com/doc/current/components/property_info.html#usage

Related