Symfony反规范化:递归反规范化不起作用



我正在尝试将以下Json结构初始化为Profile对象

{
"label": "lorem label",
"info": {
"name": "lorem name",
"title": "lorem title"
}
}

我有一个Profile

namespace AppDocument;
class profile
{
/**
* @var string
*/
protected $label;
/**
* @var Info
*/
protected $info;
// getters and setters
}

和CCD_ 3类

namespace AppDocument;
class Info
{
/**
* @var string
*/
protected name;
/**
* @var string
*/
protected title;
// getters & setters
}

我的控制器代码是以下

use SymfonyComponentSerializerEncoderJsonEncoder;
use SymfonyComponentPropertyInfoExtractorReflectionExtractor;
use SymfonyComponentPropertyInfoExtractorPhpDocExtractor;
use SymfonyComponentSerializerNormalizerObjectNormalizer;
use SymfonyComponentSerializerSerializer;
use AppDocument;
public function addProfile(Request $request, DocumentManager $dm, $profile_id)
{
$phpDocNormalizer = new ObjectNormalizer(null, null, null, new PhpDocExtractor());
$reflectionNormalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
$serializer = new Serializer([$phpDocNormalizer, $reflectionNormalizer], [new JsonEncoder()]);
$profile = $serializer->deserialize($request->getContent(), Profile::class, 'json');
return new JsonResponse(Response::HTTP_CREATED);
}

正如symfony文档所说,我已经设置了phpDocExtractor并正在工作,还设置了文档注释,还安装了PropertyInfo Component。但我一直收到这个NotNormalizableValueException:

The type of the "info" attribute for class "AppDocumentProfile" must be one of "AppDocumentInfo" ("array" given).

我已经被这个问题困扰了一段时间,任何帮助都非常感谢。

public function addProfile(Request $request, DocumentManager $dm, $profile_id)
{
$extractors = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizer = new ObjectNormalizer(null, null, null, $extractors);
$serializer = new Serializer([$normalizer], [new JsonEncoder()]);
$profile = $serializer->deserialize($request->getContent(), Profile::class, 'json');
return new JsonResponse(Response::HTTP_CREATED);
}

您可以在此处找到更详细的示例:https://symfony.com/doc/current/components/property_info.html#usage

最新更新