Convert single entity to an array

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


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.


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" ]

Tags:

Symfony