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

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

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

  1. class Tags
  2. {
  3. private array $tags;
  4. public function addTag(Tag $tag): bool{}
  5. public function removeTag(Tag $tag): bool{}
  6. public function setTags(array $tags): self{}
  7. public function getTags(): array{}

而且序列号正确。

  1. {
  2. "tags": [
  3. {
  4. "slug": "a_tag",
  5. "name": "A Tag",
  6. "description": "This is a nice tag!"
  7. }
  8. ]
  9. }

为了证明我做的:

  1. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  2. use Symfony\Component\Serializer\Encoder\JsonEncode;
  3. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  4. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  5. use Symfony\Component\Serializer\Serializer;
  6. $json = file_get_contents($this->fileName);
  7. $encoders = [new JsonEncoder()];
  8. $normalizers = [new ObjectNormalizer(null, null, null, new ReflectionExtractor())];
  9. $serializer = new Serializer($normalizers, $encoders);
  10. return $serializer->deserialize($json, Tags::class, 'json');

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

t3psigkw

t3psigkw1#

你需要使用一个ArrayDenormalizer。

  1. use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
  2. $json = file_get_contents($this->fileName);
  3. $encoders = [new JsonEncoder()];
  4. $normalizers = [
  5. new ArrayDenormalizer(),
  6. new ObjectNormalizer(null, null, null, new ReflectionExtractor())
  7. ];
  8. $serializer = new Serializer($normalizers, $encoders);
  9. return $serializer->deserialize($json, Tags::class, 'json');
at0kjp5o

at0kjp5o2#

在Symfony yaml config中尝试此配置。

  1. services:
  2. property_normalizer:
  3. class: Symfony\Component\Serializer\Normalizer\PropertyNormalizer
  4. tags: [ serializer.normalizer ]
  5. arguments:
  6. $propertyTypeExtractor: '@Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface'
  7. object_normalizer:
  8. class: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
  9. tags: [ serializer.normalizer ]
  10. get_set_method_normalizer:
  11. class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
  12. tags: [ serializer.normalizer ]
  13. array_denormalizer:
  14. class: Symfony\Component\Serializer\Normalizer\ArrayDenormalizer
  15. tags: [ serializer.denormalizer ]

它很适合收藏。

  1. /**
  2. * @var Tag[] Tags
  3. */
  4. #[OA\Property(type: 'array', items: new OA\Items(ref: '#/components/schemas/Tag'))]
  5. #[Assert\Valid(traverse: true)]
  6. protected array $tags;
展开查看全部

相关问题