symfony - 如何在 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;
}
}
解决方案
经过几个小时的搜索,我终于找到了原因。问题是“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:我的问题没有正确提出,因为我没有正确更改属性和类名。所以我在为未来的访客提出的问题中解决了这个问题。
推荐阅读
- webpack - Webpack url-loader 对图像 url 进行编码,但会破坏文件路径
- android - 为什么 Fragments 会从它们的 Activity 中分离出来?
- node.js - Uncaught SyntaxError: Unexpected token < for JavaScript files
- android - RecyclerView Android Studio 不显示 Firebase 数据库中的数据
- javascript - 有没有办法让这个反应组件不那么冗长?
- python - 成功合并后 Pandas 返回空 DF
- maven - Cloud Build 无法使用 maven 构建简单的构建步骤
- algorithm - 用于生成“n”位二进制字符串的回溯。有人可以解释一下这里是如何进行回溯的吗?
- python - 视觉工作室代码终端样板
- arrays - 在 3 维矩阵中对 3 维数组进行求和