Decode JSON into Symfony entity
11,601
Solution 1
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.
Solution 2
I would recommend using the JMSSerializerBundle.
Its serializer is way more advanced than the serializer that the one from the Serializer Component.
Comments
-
michael almost 2 years
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.