Reputation: 153
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;
And I'm getting error:
Could not denormalize object of type Item[], no supporting normalizer found.
All like in this example - https://symfony.com/doc/current/components/serializer.html#handling-arrays Why I'm getting error?
Upvotes: 4
Views: 13255
Reputation: 181
I am injecting in factory the Denormalizer I need:
...factory class
public function __construct(AbstractObjectNormalizer $normalizer)
{
$this->normalizer = $normalizer;
}
...
public function create(array $value)
{
return $this->normalizer->denormalize($value, Item::class);
}
Upvotes: 0
Reputation: 4205
I use it like this:
The Serializer component is capable of handling arrays of objects as well. Serializing arrays works just like serializing a single object:
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}]
If you want to deserialize such a structure, you need to add the ArrayDenormalizer
to the set of normalizers. By appending [] to the type parameter of the deserialize() method, you indicate that you're expecting an array instead of a single object.
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');
Read more here: https://symfony.com/doc/current/components/serializer.html
Upvotes: 8