Symfony中的序列化和反序列化

编程入门 行业动态 更新时间:2024-10-27 19:14:57
本文介绍了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中的序列化和反序列化

本文发布于:2023-10-22 23:52:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   Symfony

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!