无法对数组进行非规范化

时间:2017-08-02 13:01:48

标签: symfony serialization

}else{   print("tableview return nil") }

我收到错误:

class Item { public $id; //..getters and setters } $data = [['id' => 1], ['id' => 2]]; $serializer = new Serializer([new GetSetMethodNormalizer(), new ArrayDenormalizer()]); $model = $serializer->denormalize($data, "Item[]"); dump($model);die;

所有内容都与此示例相同 - https://symfony.com/doc/current/components/serializer.html#handling-arrays 我为什么会收到错误?

2 个答案:

答案 0 :(得分:4)

我这样用:

处理数组

Serializer组件也能够处理对象数组。序列化数组就像序列化单个对象一样:

use Acme\Person;

$person1 = new Person();
$person1->setName('foo');
$person1->setAge(99);
$person1->setSportsman(false);

$person2 = new Person();
$person2->setName('bar');
$person2->setAge(33);
$person2->setSportsman(true);

$persons = array($person1, $person2);
$data = $serializer->serialize($persons, 'json');

// $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}]

如果要反序列化此类结构,则需要将ArrayDenormalizer添加到规范化器集。通过将[]附加到deserialize()方法的type参数,可以指示您期望的是数组而不是单个对象。

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

在此处阅读更多内容: https://symfony.com/doc/current/components/serializer.html

答案 1 :(得分:0)

我正在工厂注入我需要的Denormalizer:

...factory class 
public function __construct(AbstractObjectNormalizer $normalizer)
{   
    $this->normalizer = $normalizer;
}

...

public function create(array $value)
{
    return $this->normalizer->denormalize($value, Item::class);
}