michael michael - 1 month ago 21
PHP Question

Decode JSON into Symfony entity

Does anyone know if there is an easy way, aside from writing a custom script to decode a JSON object into a PHP entity?

I'm using the script below to encode to JSON, but when I decode it's an array and not an entity.

$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($coupon, 'json');
$session->set('json', $json);


Then I'm decoding in this manner

$session = $this->getRequest()->getSession();
$json = $session->get('json');
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
$coupon = $serializer->decode($json, 'json');


But like I said... it's no longer a Coupon entity, it's just an array.

Answer

Assuming the following works:

$session = $this->getRequest()->getSession();
$json = $session->get('json');
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
$coupon = $serializer->decode($json, 'json');

$coupon is a normalized array of the serialized data. Then assuming the class you want this data to be instantiated of is called Coupon, you need to denormalize it:

$coupon = $serializer->denormalize($coupon, 'Coupon');

Mind the namespaces, the classname Coupon might not be correct.