开发者

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, bu开发者_开发知识库t 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.


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.


I would recommend using the JMSSerializerBundle.

Its serializer is way more advanced than the serializer that the one from the Serializer Component.


Another interesting option with JSON class hinting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜