【问题标题】:How to denormalize an array recursively in Symfony 5?如何在 Symfony 5 中递归地对数组进行非规范化?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2019-10-27
    • 2021-09-05
    • 2016-06-02
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2015-05-14
    相关资源
    最近更新 更多