Symfony4搭配API Platform使用transformer时GET结果为空如何解决
问题根本原因
你在@ApiResource的normalizationContext中指定了序列化组为frontend:read,序列化器只会输出带有该组注解的字段,而你自定义的EntityApiOutput输出类的属性没有添加对应的序列化组注解,所有字段都会被过滤,最终返回空响应。
解决方案
给EntityApiOutput类的所有需要返回的属性添加@Groups注解,示例如下:
<?php namespace App\Dto; // 替换为你自己的命名空间 use Symfony\Component\Serializer\Annotation\Groups; class EntityApiOutput { /** * @Groups({"frontend:read"}) */ public $id; /** * 后续需要补全路径的logo字段同样添加该注解即可 * @Groups({"frontend:read"}) */ public $logo; }
可选检查项
如果添加注解后仍返回空,可排查以下两点:
- 确认
EntityApiOutput的属性为public,或者private属性配有对应的公开getter方法 - 确认导入的
Groups注解命名空间正确,没有导错类
内容的提问来源于stack exchange,提问作者Saerdn
相关产品推荐
相关产品推荐

