序列化程序 return 错误 500(未找到支持的规范化程序)

Serializer return an error 500 (no supporting normalizer found)

我想在我的 Symfony 项目中将一个对象转换为 JSON,我在我的方法中使用了 SerializerInterface。

这是我的方法:

     /**
     * @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);
    }

这个dd(); return 我的错误 500 :

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

我在我的控制器中添加了 'use',我测试了在实体 'ProductList' 中添加组并使用此代码进行测试,但结果相同: $productListJSON = $serializer->serialize($productList, 'json', ['groups' => 'list_json']);

我不明白为什么会出现这个错误。

感谢帮助

您忘记使用正确的规范器初始化您的序列化器。

修改您的代码以添加 JsonEncoder 作为编码器和推荐的 ObjectNormalizer 作为标准化器:

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);
}

documentation 中查看更多信息。