【发布时间】:2022-01-17 13:13:46
【问题描述】:
我有一个类似这样的 JSON 对象:
{
"things": [
{"type":"custom"},
{"type":"another"}
]
}
我正在使用 Symfony Serializer 组件将 JSON 数据序列化为 PHP 对象(或类)。
现在我有这个:
class Company {
private array $things = [];
public function setThings(array $thing): void {
$this->things = $thing;
}
public function addThing(Thing $thing): void {
$this->things[] = $thing;
}
public function getThings(): array {
return $this->things;
}
}
class Thing {
public string $type;
}
$serializer = new Serializer(
[
new ArrayDenormalizer(),
new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
],
[new JsonEncoder()],
);
$deserialized = $serializer->deserialize($json, Company::class, 'json');
这会正确地将 JSON 数据序列化为具有 2 个 Thing 类实例的 Company 实例,但我想使用基于 type 属性的自定义 thing 类。
{"type": "custom"} should return an instance of CustomType (extends Type of course)
{"type": "another"} should return an instance of Another (extends Type of course)
我该如何处理?
(顺便说一句,我没有使用 Symfony 框架,只是使用了 Serializer 组件。我使用的是 Laravel 框架)。
【问题讨论】:
标签: php symfony serialization