3
votes

I have some troubles getting the xml output I expect using jms serializer and symfony 3.

I have an entity called "reference". Using the annotation @XmlRoot("reference") and returning one object only, the xml output of fos rest bundle is as expected:

<reference>
  <id>1</id>
  <title>Title 1</title>
</reference>

But if I output an array of the same objects (returned by doctrines findAll() method) I get this:

<result>
  <entry>
    <id>1</id>
    <title>Title 1</title>
  </entry>
  <entry>
    <id>2</id>
    <title>Title 2</title>
  </entry>
  <entry>
    <id>3/id>
    <title>Title 3</title>
  </entry>
</result>

The tag is called <entry> but I'd like to achieve this:

<result>
      <reference>
        <id>1</id>
        <title>Title 1</title>
      </reference>
      <reference>
        <id>2</id>
        <title>Title 2</title>
      </reference>
      <reference>
        <id>3/id>
        <title>Title 3</title>
      </reference>
 </result>

(I don't know how to use @XmlList in this case, because I do not have a parent entity holding the reference items...)

Thank you!

1

1 Answers

3
votes

First of all your expected XML is not well formatted to me. The id should be an atribute instead. The example below does it. See the result at the bottom. If you want more examples then check links below which would teach you a lot.

Result

namespace Application/YourBundle/Model;

use Application/YourBundle/Model/Reference;
use JMS\Serializer\Annotation as Serializer;

/**
 * @Serializer\XmlRoot("result")
 */
class Result
{
    /**
     * @var Reference[]
     *
     * @Assert\Valid(traverse="true")
     *
     * @Serializer\XmlList(inline=false, entry="reference")
     * @Serializer\Type("array<Application\YourBundle\Model\Reference>")
     */
    public $references = [];
}

Reference

namespace Application/YourBundle/Model;

use JMS\Serializer\Annotation as Serializer;

class Reference
{
    /**
     * @var int
     *
     * @Serializer\Type("integer")
     * @Serializer\XmlAttribute
     */
    public $id;

    /**
     * @var string
     *
     * @Serializer\Type("string")
     * @Serializer\XmlValue
     */
    public $title;
}

This setup should give you:

<result>
   <references>
      <reference id="1">Title 1</reference>
      <reference id="2">Title 2</reference>
      <reference id="3">Title 3</reference>
   </references>
</result>

If your response was a json object then it would be like this:

{
    "references": [
        {
            "id": 1,
            "title": "Title 1"
        },
        {
            "id": 2,
            "value": "Title 2"
        },
        {
            "id": 3,
            "value": "Title 3"
        }
    ]
}