4

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.

1
  • 1
    decode will always return an array, you need to denormalize the data then which will turn it into a class. Commented Sep 20, 2011 at 10:29

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hmm.. thats close, but there are entities within the Coupon class. These are set using setCity($city City) for example, and instead of passing in the object it trys to pass in the Array with all of cities attributes (id, cityname, state etc). I'm thinking I'll have to parse the entire thing by hand ;/
Well I won't go that far, but just denormalize the sub-values before you denomarlize the main array. That should do it.
1

I would recommend using the JMSSerializerBundle.

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

1 Comment

Could you please list the differences and or pros/cons between the components in your answer ? It's difficult to appreciate its quality with only way more advanced.
0

Another interesting option with JSON class hinting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.