php SYMFONY反序列化器错误:类的属性类型必须是“Object[]”之一,但(“array”给定)

dsf9zpds  于 2023-10-15  发布在  PHP
关注(0)|答案(2)|浏览(81)

我有一个标签模型(不是实体),它有一个子标签模型数组属性。

class Tags
{
    private array $tags;

    public function addTag(Tag $tag): bool{}

    public function removeTag(Tag $tag): bool{}

    public function setTags(array $tags): self{}

    public function getTags(): array{}

而且序列号正确。

{
    "tags": [
        {
            "slug": "a_tag",
            "name": "A Tag",
            "description": "This is a nice tag!"
        }
    ]
}

为了证明我做的:

use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

        $json = file_get_contents($this->fileName);
        $encoders = [new JsonEncoder()];
        $normalizers = [new ObjectNormalizer(null, null, null, new ReflectionExtractor())];
        $serializer = new Serializer($normalizers, $encoders);

        return $serializer->deserialize($json, Tags::class, 'json');

但是当我尝试去验证时,我得到了一个错误:
类“App\Model\Tags”的“tags”属性的类型必须是“App\Model\Tag[]”(给定“array”)之一。
这根本说不通在PHP中不能输入数组,那么为什么它会给出这个错误呢?
我认为这与递归反规范化和类型安全有关,但我不知道如何修复它。
Thanks in advance

t3psigkw

t3psigkw1#

你需要使用一个ArrayDenormalizer。

use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;

        $json = file_get_contents($this->fileName);

        $encoders = [new JsonEncoder()];
        $normalizers = [
            new ArrayDenormalizer(),
            new ObjectNormalizer(null, null, null, new ReflectionExtractor())
        ];
        $serializer = new Serializer($normalizers, $encoders);

        return $serializer->deserialize($json, Tags::class, 'json');
at0kjp5o

at0kjp5o2#

在Symfony yaml config中尝试此配置。

services:
  property_normalizer:
    class: Symfony\Component\Serializer\Normalizer\PropertyNormalizer
    tags: [ serializer.normalizer ]
    arguments:
      $propertyTypeExtractor: '@Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface'
  object_normalizer:
    class: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
    tags: [ serializer.normalizer ]
  get_set_method_normalizer:
    class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    tags: [ serializer.normalizer ]
  array_denormalizer:
    class: Symfony\Component\Serializer\Normalizer\ArrayDenormalizer
    tags: [ serializer.denormalizer ]

它很适合收藏。

/**
     * @var Tag[] Tags
     */
    #[OA\Property(type: 'array', items: new OA\Items(ref: '#/components/schemas/Tag'))]
    #[Assert\Valid(traverse: true)]
    protected array $tags;

相关问题