Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Serializer component: Deserialize array of objects of mixed types

I would like to know if there is a method to deserialize an array containing objects of different types. I built something where I can serialize and deserialize an array of objects of a specific type like this:

$nodes = [
    new PostNode(),
    new PostNode(),
    new PostNode()
];

$serializer = new Serializer( [
    new ObjectNormalizer(),
    new ArrayDenormalizer(),
], [ new JsonEncoder() ] ); 

$data = $serializer->serialize($nodes, 'json');

$deSerializedNodes = $serializer->deserialize( $data, PostNode::class . '[]', 'json' );

I get exactly the array back that I inserted so that is good. Now I want to know if I can serialize and deserialize an array like this:

$nodes = [
    new PostNode(),
    new PostNode(),
    new PostNode(),
    new FormNode(),
    new FormNode()
];
like image 735
jrswgtr Avatar asked Mar 08 '18 12:03

jrswgtr


1 Answers

You can only serialize an array of multiple object types as following:

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

$array = [new Foo('Radhi'), new Bar(26)];

$json = $serializer->serialize($array, 'json');

but for deserializing an array of different object types, it's not clear for the serializer, especially for objects that have the same getters/setters method names, so I think you need to do some additional configuration for that specific use case.

Check Serializing Interfaces and Abstract Classes for more details.

like image 156
Mohamed Radhi Guennichi Avatar answered Oct 22 '22 03:10

Mohamed Radhi Guennichi