jin*_*ini 2 php json symfony fosrestbundle
这是我们的控制器:
function getLocationsAction(Request $request) {
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$query = $dm->createQueryBuilder('MainClassifiedBundle:Location')->select('name', 'state', 'country', 'coordinates');
$locations = $query->getQuery()->execute();
$data = array(
'success' => true,
'locations' => $locations,
'displaymessage' => $locations->count() . " Locations Found"
);
$view = View::create()->setStatusCode(200)->setData($data);
return $this->get('fos_rest.view_handler')->handle($view);
}
Run Code Online (Sandbox Code Playgroud)
这是fosrestbundle的config.yml:
fos_rest:
view:
formats:
json: true
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
Run Code Online (Sandbox Code Playgroud)
这是路线:
MainClassifiedBundle_get_locations:
pattern: /locations/
defaults: { _controller: MainClassifiedBundle:ClassifiedCrudWebService:getLocations, _format:json}
requirements:
_method: GET
Run Code Online (Sandbox Code Playgroud)
为什么我们得到text/html?我们可以强制将响应强制为application/json吗?
请帮忙,因为这会造成巨大的痛苦
Nic*_*ich 11
您正在静态创建视图,但未启用任何侦听器.
这种方式不涉及格式猜测.
将格式作为参数传递给函数,并在View对象上设置格式:
function getLocationsAction(Request $request, $_format) {
{
// ...
$view = View::create()
->setStatusCode(200)
->setData($data)
->setFormat($_format) // <- format here
;
return $this->get('fos_rest.view_handler')->handle($view);
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档章节视图层.
如果您想要自动格式猜测,则必须启用侦听器.
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
Run Code Online (Sandbox Code Playgroud)
阅读" 监听器支持 "一章.