Convert single entity to an array

2020-07-17 15:44发布

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 ?

标签: symfony
4条回答
啃猪蹄的小仙女
2楼-- · 2020-07-17 16:16

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

查看更多
贪生不怕死
3楼-- · 2020-07-17 16:16

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

$data = array:[ "success" => true "errorMessage" => null "result" => "1" "type" => "url" ]

查看更多
虎瘦雄心在
4楼-- · 2020-07-17 16:18

You can also just create a public routine in the entity itself which is similar to what serializer is doing.

查看更多
Viruses.
5楼-- · 2020-07-17 16:34

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.

查看更多
登录 后发表回答