Add extra fields using JMS Serializer bundle

后端 未结 6 1406
说谎
说谎 2020-12-13 04:03

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

6条回答
  •  误落风尘
    2020-12-13 04:32

    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);
        }
    
    
    }
    

提交回复
热议问题