Symfony3反序列化多个实体对象

时间:2016-12-04 21:31:17

标签: serialization symfony php-7

对我来说,正确地序列化和反序列化单个实体对象。

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

$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 \分量\ PropertyAccess \的PropertyPath”。得到:“整数”500   内部服务器错误 - UnexpectedValueException

1 个答案:

答案 0 :(得分:5)

我找到了解决方案

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');