简体   繁体   English

使用 Symfony 串行器解析为自定义类型

[英]Resolve to custom type with Symfony serializer

I have a JSON object something like this:我有一个 JSON object 是这样的:

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

I'm using the Symfony Serializer component to serialize that JSON data into PHP objects (or classes).我正在使用 Symfony 序列化器组件将 JSON 数据序列化为 PHP 对象(或类)。

Right now I have this:现在我有这个:

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');

This correctly serializes the JSON data into a Company instance with 2 instances of the Thing class but I'd like to use a custom thing class based on the type property.这会正确地将 JSON 数据序列化到一个Company实例中,其中包含 2 个Thing class 实例,但我想使用基于 type 属性的自定义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)

How do I handle this?我该如何处理?

(btw, I'm not using the Symfony framework, just the Serializer component. I do use the Laravel framework). (顺便说一句,我没有使用 Symfony 框架,只是串行器组件。我使用的是 Laravel 框架)。

I would suggest creating a custom normalizer.我建议创建一个自定义规范器。 See https://symfony.com/doc/current/serializer/custom_normalizer.html请参阅https://symfony.com/doc/current/serializer/custom_normalizer.html

Put a mapping array into this normalizer which maps the different "type" values to their corresponding class names.将一个映射数组放入此规范器中,它将不同的“类型”值映射到它们对应的 class 名称。 You can then use this information to normalize the data into an object of the desired class.然后,您可以使用此信息将数据标准化为所需 class 的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM