英文:
Symfony serializer - Deserialize xml to array of objects
问题
以下是您要翻译的内容:
php Symfony序列化器 - 将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');
Item类:
class Item
{
#[SerializedName('@flight')]
public string $flight;
}
现在的结果:
array:1 [
"item" => App\Entities\Item
]
英文:
php Symfony serializer - Deserialize xml to array of objects
How deserialize xml with attributes to array of objects?
$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');
Item class:
class Item
{
#[SerializedName('@flight')]
public string $flight;
}
Now result:
array:1 [
"item" => App\Entities\Item
]
答案1
得分: 0
你必须两次输入方括号。
$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']);
}
英文:
You must enter the square brackets twice.
$objects = $serializer->deserialize($string, 'App\Tests\Item[][]', 'xml')
Or the following. But it is basically the same thing.
$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']);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论