【问题标题】:Resolve to custom type with Symfony serializer [duplicate]使用 Symfony 序列化程序解析为自定义类型 [重复]
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多