簡體   English   中英

使用 Symfony 串行器解析為自定義類型

[英]Resolve to custom type with Symfony serializer

我有一個 JSON object 是這樣的:

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

我正在使用 Symfony 序列化器組件將 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 數據序列化到一個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)

我該如何處理?

(順便說一句,我沒有使用 Symfony 框架,只是串行器組件。我使用的是 Laravel 框架)。

我建議創建一個自定義規范器。 請參閱https://symfony.com/doc/current/serializer/custom_normalizer.html

將一個映射數組放入此規范器中,它將不同的“類型”值映射到它們對應的 class 名稱。 然后,您可以使用此信息將數據標准化為所需 class 的 object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM