dam*_*123 5 php rest json symfony fosrestbundle
我正在学习使用 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);
}
Run Code Online (Sandbox Code Playgroud)
但后来我尝试使用 fost Rest 的视图处理程序(在 config.yml 中)直接序列化 $places
fos_rest:
routing_loader:
include_format: false
view:
view_response_listener: true
format_listener:
rules:
- { path: '^/', priorities: ['json'], fallback_format: 'json' }
Run Code Online (Sandbox Code Playgroud)
并将我的控制器中的函数更改为以下代码,我得到了我的 JSON 响应,但在“{ [],[],[]}”之间没有任何内容(我的数据库中有 3 个条目):
public function getPlacesAction(Request $request)
{
$places = $this->get('doctrine.orm.entity_manager')
->getRepository('AppBundle:Place')
->findAll();
/* @var $places Place[] */
return $places;
}
Run Code Online (Sandbox Code Playgroud)
这是我在 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 }
Run Code Online (Sandbox Code Playgroud)
我仍然不明白为什么它有效,但突然间我得到了一个很好的 json 响应。
归档时间: |
|
查看次数: |
1412 次 |
最近记录: |