【发布时间】:2020-09-06 08:29:59
【问题描述】:
我需要从 YAML 文件中反序列化对象的索引数组。问题是 symfony 认为它是items 中的一堆对象,但它是带有索引的数组,并且总会有不同的名称(索引)。我在文档中找不到答案(很确定我只是忽略了)。
有什么建议吗?
YAML:
items:
darkvoice:
display_name: Dark Voice
price: 100
phone:
display_name: Mobile phone
price: 100
映射
$encoders = [ new YamlEncoder() ];
$normalizers = [
new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
];
$serializer = new Serializer($normalizers, $encoders);
$test = $serializer->deserialize(file_get_contents(__DIR__.'/example.yml'), ItemList::class, 'yaml');
类
class ItemList {
/** @var Singleton[] */
private array $items = [];
/**
* @return Singleton[]
*/
public function getItems(): array
{
return $this->items;
}
/**
* @param Singleton[] $items
* @return ItemList
*/
public function setItems($items): self
{
$this->items = $items;
return $this;
}
}
class Singleton {
private string $display_name;
private int $price = 0;
/**
* @return string
*/
public function getDisplayName(): string
{
return $this->display_name;
}
/**
* @param string $display_name
* @return Singleton
*/
public function setDisplayName($display_name):self
{
$this->display_name = $display_name;
return $this;
}
/**
* @return int
*/
public function getPrice(): int
{
return $this->price;
}
/**
* @param int $price
* @return Singleton
*/
public function setPrice(int $price): Singleton
{
$this->price = $price;
return $this;
}
}
【问题讨论】:
-
symfony.com/doc/current/components/serializer.html 如您在最顶部看到的,如果您反序列化输出是一个对象。将你的 YAML 解码成一个数组:)
标签: php symfony serialization