我正在学习使用 symfony 构建 API(使用 FOSRestBundle)。我正在学习法语教程。显然,我首先尝试自己编写代码,但即使使用复制/粘贴,当我向适当的路由 (rest-api.local/places) 发出 GET 请求时,它仍然让我得到空的 JSON 数组。
如果我在 php 数组中“格式化”代码,代码工作正常:
public function getPlacesAction(Request $request)
{
$places = $this->get('doctrine.orm.entity_manager')
->getRepository('AppBundle:Place')
->findAll();
/* @var $places Place[] */
$formatted = [];
foreach ($places as $place) {
$formatted[] = [
'id' => $place->getId(),
'name' => $place->getName(),
'address' => $place->getAddress(),
];
}
return new JsonResponse($formatted);
}
但随后我尝试使用 fost Rest 的 View 处理程序(在 config.yml 中)直接序列化 $places
fos_rest:
routing_loader:
include_format: false
view:
view_response_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: 'json' }
并将 Controller 中的函数更改为以下代码,我得到了 JSON 响应,但“{ [],[],[]}”之间没有任何内容(我的数据库中确实有 3 个条目):
public function getPlacesAction(Request $request)
{
$places = $this->get('doctrine.orm.entity_manager')
->getRepository('AppBundle:Place')
->findAll();
/* @var $places Place[] */
return $places;
}
这是我关于 stackoverflow 的第一篇文章,所以我希望我的问题很清楚,祝你有愉快的一天。
最佳答案
在我的 app/config/services.yml
中,我添加了这个:
services:
object_normalizer:
class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
# Important! Tag this service or it wouldn't work
tags:
- { name: serializer.normalizer }
我仍然不明白为什么它会起作用,但突然之间我得到了一个很好的 json 作为响应。
关于php - symfony/FOSRestBundle : empty JSON response (using the symfony embodied serializer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507035/