首页 > 解决方案 > 如何在 Symfony 5 中递归地对数组进行非规范化?

问题描述

我目前正在尝试对一个数组进行非规范化,该数组作为 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;
    }
}

标签: symfonyrecursionserializationdenormalization

解决方案


经过几个小时的搜索,我终于找到了原因。问题是“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:我的问题没有正确提出,因为我没有正确更改属性和类名。所以我在为未来的访客提出的问题中解决了这个问题。


推荐阅读