8

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()
];

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.