问题描述
我目前正在尝试对一个数组进行非规范化,该数组作为 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;
}
}
解决方法
经过几个小时的搜索,我终于找到了原因。问题是“inner_property”蛇形外壳和 $innerProperty 或 getInnerProperty 驼色外壳的组合。在 Symfony 5 中,默认情况下不启用骆驼案例到蛇案例转换器。
所以我必须通过在 config/packages/framework.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
或者,我也可以向 Outer 类中的属性添加一个 SerializedName 注释: https://symfony.com/doc/current/components/serializer.html#configure-name-conversion-using-metadata
PS:我的问题没有正确提出,因为我没有正确更改属性和类名称。所以我在问题中为未来的访问者解决了这个问题。