Home > Mobile >  Serializer return an error 500 (no supporting normalizer found)
Serializer return an error 500 (no supporting normalizer found)

Time:11-22

I want transform an object to JSON in my Symfony project, I use the SerializerInterface in my method.

Here is my method:

     /**
     * @Route("{token}", name="list")
     */
    public function list(ProductList $productList, ProductRepository $productRepository, SerializerInterface $serializer): Response
    {
        $productListJSON = $serializer->serialize($productList, 'json');
        dd($productListJSON);

        return $this->json($productListJSON);
    }

This dd(); return me an error 500 :

Could not normalize object of type "App\Entity\ProductList", no supporting normalizer found.

I have add 'use' in my Controller, I have test to add Group in the entity 'ProductList' and test with this code, but same result : $productListJSON = $serializer->serialize($productList, 'json', ['groups' => 'list_json']);

I don't understand why I have this error.

Thanks for the help

CodePudding user response:

You forgot to initialize your serializer with the proper Normalizer.

Modify your code to add JsonEncoder as encoder and the recommended ObjectNormalizer as normalizer:

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

 /**
 * @Route("{token}", name="list")
 */
public function list(ProductList $productList, ProductRepository $productRepository): Response
{
    $encoders = [new JsonEncoder()];
    $normalizers = [new ObjectNormalizer()];
    $serializer = new Serializer($normalizers, $encoders);

    $productListJSON = $serializer->serialize($productList, 'json');
    dd($productListJSON);

    return $this->json($productListJSON);
}

See more in the documentation.

  • Related