【问题标题】:Symfony3 deserialize multiple entity objectsSymfony3 反序列化多个实体对象
【发布时间】:2016-12-04 21:31:16
【问题描述】:

序列化和反序列化单个实体对象对我来说正常工作。

这种方式可以序列化和反序列化多个对象(对象数组)吗??

$notifications = $this->getDoctrine()
    ->getRepository('AppBundle:Notification')
    ->findAll();

$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();

$serializer = new Serializer(array($normalizer), array($encoder));
$jsonContent = $serializer->serialize($notifications, 'json');

return new Response($jsonContent);

$response = curl_exec($ch); // my $jsonContent from previous code

$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();

$serializer = new Serializer(array($normalizer), array($encoder));
$notifications = $serializer->deserialize($response, Notification::class, 'json');

然后我得到了:

属性路径构造函数需要一个字符串或一个实例 “Symfony\Component\PropertyAccess\PropertyPath”。得到:“整数” 500 内部服务器错误 - UnexpectedValueException

【问题讨论】:

  • Will 听起来很愚蠢,但错误消息确实告诉了您一切……您的属性路径构造函数正在等待 PropertyPath 的一个实例,它是 PropertyAccess 的子代。但是,您的构造函数得到一个 Integer 作为参数,这显然是错误的。您可以在您的问题中添加您的构造函数以及与之相关的所有内容吗?

标签: serialization symfony php-7


【解决方案1】:

我找到了解决办法

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer(
    array(new GetSetMethodNormalizer(), new ArrayDenormalizer()),
    array(new JsonEncoder())
);

$data = ...; // The serialized data from the previous example
$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');

【讨论】:

  • 您好,对于仍然希望使用 Symfony 序列化器(以及最重要的反序列化器)的人们,我发现:medium.com/@maartendeboer/…
猜你喜欢
  • 2013-05-01
  • 2013-04-15
  • 2016-07-09
  • 2011-09-26
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
相关资源
最近更新 更多