0

I cant figure out how to deserialize this xml with the symfony serializer

<?xml version="1.0" encoding="UTF-8"?>
<issues>
  <issue id="1" name="test">
    <page id="0" name="page 0"/>
    <page id="1" name="page 1"/>
    <page id="2" name="page 2"/>
    ....
  </issue>
</issues>

I created entitys for issue and page like that

class Issue
{
    #[ORM\Id]
    #[ORM\Column]
    #[SerializedName('issue/@id')]
    private ?int $id = null;

    #[ORM\Column(length: 255, nullable: true)]
    #[SerializedName('issue/@name')]
    private ?string $name = null;

    #[ORM\OneToMany(mappedBy: 'issue', targetEntity: Page::class)]
    #[SerializedPath('issue/page')]
    private Collection $Pages;
    .....
}

And the serializer is set up like that

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
        $normalizers = [
            new ArrayDenormalizer(),
            new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter, null, new ReflectionExtractor())
        ];
        $encoders = [new XmlEncoder()];
        
        $serializer = new Serializer($normalizers, $encoders);

        $issues = $serializer->deserialize($xml, Issue::class, 'xml', [
            'xml_root_node_name' => 'issues',

        ]);

but i only get back a empty result:

^ App\Entity\Issue {#184 ▼
  -id: null
  -name: null
  -Pages: Doctrine\Common\Collections\ArrayCollection {#140 ▼
    -elements: []
  }
}
23nr1
  • 11
  • 2

1 Answers1

0

First, remove issue/ in the values passed in the #SerializedName like this in your Issue class :

#[SerializedName('@id')]
private ?int $id = null;

And for the collection of pages :

#[SerializedPath('[page]')]
private Collection $pages;

You also need to tell to the deserialize method you want an array of issues, not just one :

$issues = $serializer->deserialize($xml, Issue::class.'[]', 'xml', [
    'xml_root_node_name' => 'issues',
]);

Note that you will need to create a setId() method in your Issue class to populate the id, same for Page.

Thomas
  • 410
  • 9
  • 14