Symfony中的序列化和反序列化 [英] Serializing and Deserializing in Symfony
本文介绍了Symfony中的序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Symfony捆绑包"symfony/serializer"对实体进行序列化.
I am serializing entities with the Symfony bundle "symfony/serializer".
我能够毫无问题地将我的实体编码为json,但是我在反序列化并将其恢复为原始格式时遇到了问题.我收到的错误是;
I am able to encode my entity into json with no problems, however I am having problems deserializing it and bringing it back into its original form. The error I am receiving is;
Could not denormalize object of type AppBundle:Entity, no supporting normalizer found.
DefaultController.php
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
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;
}
}
不太确定我缺少什么,任何帮助将不胜感激.
Not too sure what I am missing, any help greatly appreciated.
推荐答案
deserialize()应该获取实体的名称空间,因此您需要进行更改
AppBundle:Entity
至AppBundle\Entity
.
deserialize() should get the namespace of the entity so you need to change
AppBundle:Entity
to AppBundle\Entity
.
$person = $serializer->deserialize($jsonContent, 'AppBundle\Entity', 'json');
这篇关于Symfony中的序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文