Symfony serializer -将xml反序列化为对象数组

afdcj2ne  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(197)

php Symfony serializer -将xml反序列化为对象数组
如何将带有属性的xml反序列化为对象数组?

$string = '<?xml version="1.0" encoding="UTF-8" ?>
<response>
    <item flight="23"/>
    <item flight="24"/>
</response>';

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);

        $serializer = new Serializer(
            [new ArrayDenormalizer(), new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
            [new XmlEncoder()]
        );
$objects = $serializer->deserialize($string, 'App\Entities\Item[]', 'xml');

物品类别:

class Item
{
    #[SerializedName('@flight')]
    public string $flight;
}

现在结果:

array:1 [
  "item" => App\Entities\Item
]
wkftcu5l

wkftcu5l1#

必须输入两次方括号。

$objects = $serializer->deserialize($string, 'App\Tests\Item[][]', 'xml')

或者下面的。但基本上是一回事。

$xmlContent = '
    <response>
        <item flight="23"/>
        <item flight="24"/>
    </response>
';

class Item
{
    public string $flight;

    /**
     * @param string $flight
     */
    public function __construct(string $flight)
    {
        $this->flight = $flight;
    }

    /**
     * @return string
     */
    public function getFlight(): string
    {
        return $this->flight;
    }
}

$flights = [];
$encoders = [new XmlEncoder()];
$serializer = new Serializer([], $encoders);
$response = $serializer->decode($xmlContent, "xml");
foreach ($response['item'] as $item) {
    $flights[] = new Item($item['@flight']);
}

相关问题