目前,我正试图对一个数组进行去of化,该数组作为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;
}
}
发布于 2021-02-15 14:36:37
经过几个小时的搜索,我终于找到了原因。问题是"inner_property“蛇案和$innerProperty或getInnerProperty骆驼案的结合。在Symfony 5中,默认情况下不启用camel case到snake case转换器。
因此,我不得不在config/packages/framework.yaml work.yaml中添加这个配置。
framework:
serializer:
name_converter: 'serializer.name_converter.camel_case_to_snake_case'
以下是对Symfony文档的引用:https://symfony.com/doc/current/serializer.html#enabling-a-name-converter
或者,我也可以向外层类中的属性添加一个SerializedName注释:https://symfony.com/doc/current/components/serializer.html#configure-name-conversion-using-metadata
PS:我的问题没有被正确地问出来,因为我没有正确地更改属性和类名。所以我在问题中修正了这个问题,供未来的访客参考。
https://stackoverflow.com/questions/66201063
复制