【发布时间】:2021-05-17 22:17:09
【问题描述】:
我目前正在尝试对一个数组进行非规范化,该数组作为 JSON 响应来自 API,并已被 JSON 解码。
问题是,我希望它被非规范化为一个类,其中一个属性是另一个类。
感觉应该可以使用 Symfony 非规范化器完成如此简单的工作,但我总是遇到以下异常:
Failed to denormalize attribute "inner_property" value for class "App\Model\Api\Outer": Expected argument of type "App\Model\Api\Inner", "array" given at property path "inner_property".
我的非规范化代码如下所示:
$this->denormalizer->denormalize($jsonOuter, Outer::class);
在构造函数中注入反规范化器:
public function __construct(DenormalizerInterface $denormalizer) {
我尝试去规范化的数组:
array (
'inner_property' =>
array (
'property' => '12345',
),
)
最后,我尝试将这两个类非规范化为:
class Outer
{
/** @var InnerProperty */
private $innerProperty;
public function getInnerProperty(): InnerProperty
{
return $this->innerProperty;
}
public function setInnerProperty(InnerProperty $innerProperty): void
{
$this->innerProperty = $innerProperty;
}
}
class InnerProperty
{
private $property;
public function getProperty(): string
{
return $this->property;
}
public function setProperty(string $property): void
{
$this->property = $property;
}
}
【问题讨论】:
-
你看过symfony.com/doc/current/components/…。如果您有精力和熟练程度,您可能会找出默认设置不起作用的原因。 ^^^
-
@Jakumi 是的,我读到了,但提供的示例对我没有帮助,我无法弄清楚如何解决我自己的问题。
-
是的,链接的文档还不够。我相信您必须编写一个属性类型提取器(在文档中提到,但没有提供有关如何实现的文档),但是,我相信这篇 SO 文章/问题/答案可能会提供一些见解(尽管对于较旧的symfony 版本,但原则应该仍然适用,并且类/接口可能仍然存在)stackoverflow.com/questions/49778907/… 也许显式添加其中之一就足够了:github.com/symfony/symfony/tree/5.2/src/Symfony/Component/…
标签: symfony recursion serialization denormalization