What is the most efficient way to convert my Symfony2 entity to an array ? Entity contains protected fields with setters/getters. Is it possible to do with JMSSerializer ?
5 Answers
Using this bundle is the most efficient way to convert Entities to serialized format. Moreover, it's recommended by Sensio Labs.
To serialize You need only to install, configure this bundle and then:
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$serializer->serialize($object, 'json');
And deserialize:
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, 'MyNamespace\MyObject', 'json');
Nothing more.
You can also use it to convert an object to an array:
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$array = $serializer->toArray($object);
Also, you can prevent infinite recursion using serialization groups:
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$context = \JMS\Serializer\SerializationContext::create();
$context->setGroups($groups);
$serializer->serialize($object, 'json', $context);
Regards
5 Comments
json format. I would like to normalize it to an array.$jmsSerializer = SerializerBuilder::create()->build(); $data = $jmsSerializer->toArray($entities);ArrayCollection but when i try to use toArray() with a single entity I received this error: The input data of type "boolean" did not convert to an array, but got a result of type "boolean".. Do you know why?If you have not installed Symfony Serializer Component.
install it composer require symfony/serializer
then just convert any entity to array as follows.
$serializer = new Serializer(array(new ObjectNormalizer()));
$data = $serializer->normalize($result, null, array('attributes' =>
array('success','type','result','errorMessage')));
and the output will be,
$data = array:[ "success" => true "errorMessage" => null "result" => "1" "type" => "url" ]
Comments
Using JMSSerializer for such a simple task seems like an overkill to me. I would use Symfony Serializer Component. The demo page shows how to serialize an entity to JSON.
If you just want to put it to array, you don't need serialization at all, you could just instantiate GetSetMethodNormalizer and use it since component uses arrays as normalized format.
1 Comment
You can use Serializer Component:
$person = new Person();
$person->setName('foo');
$person->setAge(99);
$serializer = new Symfony\Component\Serializer\Serializer([new ObjectNormalizer()]);
var_dump($serializer->normalize($person));
See the documentation: https://symfony.com/doc/current/components/serializer.html#serializing-an-object
Also, you can configure the DI globally
App.ObjectNormalizer:
alias: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
Symfony\Component\Serializer\Serializer:
arguments:
$normalizers:
0: '@App.ObjectNormalizer'
and then simply call:
var_dump($serializer->normalize($person));