【发布时间】:2026-01-09 16:40:01
【问题描述】:
我正在使用 Symfony 包“symfony/serializer”序列化实体。
我能够毫无问题地将我的实体编码为 json,但是我在反序列化它并将其恢复为原始形式时遇到了问题。我收到的错误是;
Could not denormalize object of type AppBundle:Entity, no supporting normalizer found.
DefaultController.php
//Create Entity to Serialize
$entity = new Entity();
$entity->setId(1);
$entity->setName('john');
//create serializer to serialize entity
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($entity, 'json');
var_dump($jsonContent); // returns string '{"id":1,"name":"john"}' (length=22) << GOOD!
//Deserialize entity
$person = $serializer->deserialize($jsonContent, 'AppBundle:Entity', 'json');
//<ERROR HERE>//
var_dump($person);
Entity.php
namespace AppBundle\Entity;
class Entity {
private $id;
private $name;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
不太确定我错过了什么,非常感谢任何帮助。
【问题讨论】:
-
symfony 序列化程序非常有限。请查看JMS/serializer。它更强大
标签: php json symfony serialization