Search code examples
symfonyfosrestbundlejmsserializerbundlejms-serializersymfony-2.6

Add a root element name using JMS Serializer with Symfony 2.6


I have implemented web services using Symfony 2.6 with FOSRestBundle and JMSSerializerBundle.

I can't manage to have a root element named request eventhough I put xml_root_name: request in the configuration file.

I have a config\serializer\Entity.Request.yml file with the following information:

Tvjp\RequestBundle\Entity\Request:
    exclusion_policy: ALL
    xml_root_name: request
    properties:
        id:
            expose: true
            type: integer
        label:
            expose: true
            type: string
        issuer:
            expose: true
            type: string

When I try to access to a single request, this is what I get in XML :

<result>
    <id>23</id>
    <label><![CDATA[ test label ws post ]]></label>
    <issuer><![CDATA[ test issuer ws post ]]></issuer>
</result>

And what I get in json : {"id":23,"label":"test label ws post","issuer":"test issuer ws post"}

Any ideas what am I doing wrong here ?


Solution

  • I finally manage to make it work using annotations on the entity class instead of using the config\serializer\Entity.Request.ymlfile.

    So i deleted the file config\serializer\Entity.Request.yml and here is my entity Request file :

    use JMS\Serializer\Annotation\ExclusionPolicy,
        JMS\Serializer\Annotation\Expose,
        JMS\Serializer\Annotation\Type,
        JMS\Serializer\Annotation\XmlRoot;
    
    /**
     * Request
     * @ExclusionPolicy("all")
     * @XmlRoot("request") 
     */
    class Request{
    
        /**
         * @var integer
         * @Expose
         * @Type("integer")
         */
        private $id;
    
        /**
         * @var string
         * @Expose
         * @Type("string")
         */
        private $label;
    
       /**
        * @var string
        * @Expose
        * @Type("string")
        */
        private $issuer;
    
        [...]
    }