API Platform传参报错:Argument #3需string类型,实际传入int
我尝试从React代码通过API Platform的requestBody向PHP代码传递数据,但遇到无法解决的错误。错误信息如下:
"@context": "/api/contexts/Error",
"@type": "hydra:Error",
"hydra:title": "An error occurred",
"hydra:description": "ApiPlatform\Serializer\AbstractItemNormalizer::canAccessAttributePostDenormalize(): Argument #3 ($attribute) must be of type string, int given, called in /var/www/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php on line 365",
我传递的JSON数据已将所有值转为字符串,但仍报错,数据示例为:
[{"queue":"/api/queues/5","nbClients":"9","nbProcess":"5","nbCluster":"1","nbThreads":"6","studyId":"295"},{"queue":"/api/queues/5","nbClients":"9","nbProcess":"5","nbCluster":"1","nbThreads":"6","studyId":"296"},{"queue":"/api/queues/4","nbClients":"9","nbProcess":"24","nbCluster":"3","nbThreads":"6","studyId":"297"},{"queue":"/api/queues/5","nbClients":"9","nbProcess":"5","nbCluster":"1","nbThreads":"6","studyId":"298"},{"queue":"/api/queues/5","nbClients":"undefined","nbProcess":"undefined","nbCluster":"undefined","nbThreads":"undefined","studyId":"299"}]
请问问题可能出在哪里?
- 请求结构与API预期不匹配:你传递的是数组,但API可能仅支持接收单个对象。API Platform默认序列化器针对单个资源设计,若要批量提交数据,需在API资源注解中显式配置集合操作,并指定对应的集合输入DTO。否则序列化器会误将数组索引(int类型)当作属性名处理,触发当前类型错误。
- API资源配置缺失集合支持:检查PHP实体或DTO的API Platform注解,确认是否开启POST集合操作。示例配置如下:
没有专门的集合DTO时,直接传递数组会导致序列化解析失败,出现属性类型为int的错误。/** * @ApiResource( * collectionOperations={ * "post"={ * "input"=BatchInputDto::class, // 自定义集合输入DTO * } * } * ) */ - "undefined"值的潜在风险:数据中存在
"nbClients":"undefined"这类字符串值,若后端对应字段定义为数字类型,后续可能引发其他序列化异常,但当前错误的直接原因是请求结构不匹配,优先解决结构问题。
内容的提问来源于stack exchange,提问作者Docrom

