Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
michael Avatar asked Oct 18 '25 15:10

michael


1 Answers

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.

like image 98
hakre Avatar answered Oct 20 '25 05:10

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!