使用 Symfony 序列化程序解析为自定义类型

Resolve to custom type with Symfony serializer

我有一个 JSON 对象是这样的:

{
  "things": [
    {"type":"custom"},
    {"type":"another"}
  ]
}

我正在使用 Symfony Serializer 组件将 JSON 数据序列化为 PHP 对象(或 classes)。

现在我有这个:

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 数据序列化为一个 Company 实例,其中包含 2 个 Thing class 实例,但我想使用自定义 thing class 基于类型 属性.

{"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 框架)。

我建议创建一个自定义规范化器。参见 https://symfony.com/doc/current/serializer/custom_normalizer.html

将映射数组放入此规范化器中,将不同的“类型”值映射到它们对应的 class 名称。然后,您可以使用此信息将数据规范化为所需 class.

的对象