Symfony2 ObjectNormalizer denormalize callbacks
Can I use setCallbacks
on Symfony\Component\Serializer\Normalizer\ObjectNormalizer
, which is called when called Symfony\Component\Serializer\Serializer.deserialize()
to convert the normalized value back to an object?
I know the opposite is possible, in that the object can be normalized when called Symfony\Component\Serializer\Serializer.serialize()
. I just don't do reverse normalization.
An example of serialization for an object setCallbacks
converting Foo
to Id
:
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCallbacks(array(
'foo' => function ($foo) {
return $foo instanceof Foo
? $foo->getId()
: null;
},
));
$serializer = new Serializer(array($normalizer), array($encoder));
$json = $serializer->serialize($entity, 'json');
The opposite is what I would like to do:
$em = static::getEntityManager();
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCallbacks(array(
'foo' => function ($foo) use($em) {
return !is_null($foo)
? $em->getReference('\Entity\Foo', $foo)
: null;
},
));
$serializer = new Serializer(array($normalizer), array($encoder));
return $serializer->deserialize($entity, $classname, 'json');
The error I am getting:
Catchable fatal error: Argument 1 passed to \Entity\Bar::setFoo() must be an instance of \Entity\Foo, integer given
Or is there a preliminary step that can be done before deserialize
?
source to share