I\'ve an entity I usually serialize using the JMS Serializer bundle. I have to add to the serialization some fields that doesn\'t reside in the entity itself but are gathere
The accepted answer only works when the visitor is derived from \JMS\Serializer\GenericSerializationVisitor. This means it will work for JSON, but fail for XML.
Here's an example method which will cope with XML. It looks at the interfaces the visitor object supports and acts appropriately. It shows how you might add a link element to both JSON and XML serialized objects...
public function onPostSerialize(ObjectEvent $event)
{
//obtain some data we want to add
$link=array(
'rel'=>'self',
'href'=>'http://example.org/thing/1',
'type'=>'application/thing+xml'
);
//see what our visitor supports...
$visitor= $event->getVisitor();
if ($visitor instanceof \JMS\Serializer\XmlSerializationVisitor)
{
//do XML things
$doc=$visitor->getDocument();
$element = $doc->createElement('link');
foreach($link as $name => $value) {
$element->setAttribute($name, $value);
}
$doc->documentElement->appendChild($element);
} elseif ($visitor instanceof \JMS\Serializer\GenericSerializationVisitor)
{
$visitor->addData('link', $link);
}
}