我想在我的 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(); 回傳錯誤 500 :
無法規范化“App\Entity\ProductList”型別的物件,找不到支持的規范化器。
我在我的控制器中添加了“使用”,我測驗在物體“產品串列”中添加組并使用此代碼進行測驗,但結果相同:
$productListJSON = $serializer->serialize($productList, 'json', ['groups' => 'list_json']);
我不明白為什么我有這個錯誤。
謝謝您的幫助
uj5u.com熱心網友回復:
您忘記使用正確的 Normalizer 初始化序列化程式。
修改您的代碼以添加JsonEncoder為編碼器以及推薦ObjectNormalizer和規范化器:
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
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);
}
在檔案中查看更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362818.html
上一篇:使用冒泡排序對銷售團隊進行排序
