Rey*_*rPM 11 php json symfony fosrestbundle symfony-2.6
我已将FOSRestBundle配置如下:
#FOSRestBundle
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener:
rules:
- { path: ^/, priorities: [ json, html ], fallback_format: ~, prefer_extension: true }
media_type:
version_regex: '/(v|version)=(?P<version>[0-9\.]+)/'
body_converter:
enabled: true
validate: true
view:
mime_types:
json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1']
view_response_listener: 'force'
formats:
xml: false
json: true
templating_formats:
html: true
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
allowed_methods_listener: true
access_denied_listener:
json: true
Run Code Online (Sandbox Code Playgroud)
我在控制器上有这个:
namespace PDI\PDOneBundle\Controller\Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\Get;
class RepresentativeRestController extends FOSRestController
{
/**
* Get all representatives.
*
* @return array
*
* @ApiDoc(
* resource = true,
* https = true,
* description = "Get all representatives.",
* statusCodes = {
* 200 = "Returned when successful",
* 400 = "Returned when errors"
* }
* )
* @Get("/api/v1/reps")
*/
public function getRepsAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('PDOneBundle:Representative')->findAll();
if(!$entities)
{
return $this->view(null, 400);
}
return $this->view($entities, 200);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试以下URL时,app_dev.php/api/v1/reps我收到此错误:
无法找到模板"".500内部服务器错误 - InvalidArgumentException 3链接的异常:Twig_Error_Loader»InvalidArgumentException»InvalidArgumentException»
我希望API返回一个格式良好的JSON,如下例所示:
{
"id":"30000001",
"veeva_rep_id":"0055648764067SwzAAE",
"display_name":"John Know",
"avatar_url":"http://freelanceme.net/Images/default%20profile%20picture.png",
"rep_type":"VEEVA",
"username":"john@mail.com",
"first":"John",
"last":"Know",
"title":"Sales Representative",
"phone":"800-555-1212",
"email":"john@mail.com",
"territory_id":"200454001",
"inactive":"no",
"total_contacts":"6",
"total_shares":"0",
"totalViews":"0",
"lastLoginAt":"2015-05-05 15:45:57",
"lastVeevaSyncAt":"2015-05-05 15:45:57",
"createdAt":"2015-05-05 15:45:57",
"updatedAt":"2015-05-05 15:45:57"
}
Run Code Online (Sandbox Code Playgroud)
是不是为返回JSON配置了FOSRestBundle?为什么还要求Twig模板?我怎样才能解决这个问题?
第一次测试:
作为@Jeet建议我我一直在使用邮差尝试(是一样的,他告诉我的扩展名),并设置后的头Content-Type到application/json错误变成这样
格式错误的JSON
所以,FOSRestBundle没有按原样设置标头,控制器没有返回有效的JSON,我该如何解决这些问题呢?
第二次测试:
正如@Jeet建议我运行这个测试:
/**
* Get all representatives.
*
* @return array
*
* @ApiDoc(
* resource = true,
* https = true,
* description = "Get all representatives.",
* statusCodes = {
* 200 = "Returned when successful",
* 400 = "Returned when errors"
* }
* )
* @Get("/api/v1/reps")
* @View()
*/
public function getRepsAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('PDOneBundle:Representative')->findAll();
$temp = array("1", "2", "3");
$view = $this->view($temp, Codes::HTTP_OK);
return $this->handleView($view);
}
Run Code Online (Sandbox Code Playgroud)
仍然是同一个问题:
无法找到模板"".500内部服务器错误 - InvalidArgumentException 3链接的异常:Twig_Error_Loader»InvalidArgumentException»InvalidArgumentException»
还有什么可能是错的?我在配置上遗漏了什么吗?
我忘记了添加app/config/routing.yml,src/PDI/PDOneBundle/Resources/config/routing.yml所以在这里他们去了,也许这是拼图上的缺失部分,让你更好地了解问题的来源:
#app/config/routing.yml
#PDOne
pdone:
resource: "@PDOneBundle/Resources/config/routing.yml"
template:
resource: "@TemplateBundle/Resources/config/routing.yml"
#FOSUserBundle
fos_user:
resource: "@FOSUserBundle/Resources/config/routing/all.xml"
prefix: /
#NelmioApiDocBundle:
NelmioApiDocBundle:
resource: "@NelmioApiDocBundle/Resources/config/routing.yml"
prefix: /api/doc
#SonataAdmin
admin:
resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
prefix: /admin
_sonata_admin:
resource: .
type: sonata_admin
prefix: /admin
#src/PDI/PDOneBundle/Resources/config/routing.yml
pdone:
resource: "@PDOneBundle/Controller/"
type: annotation
prefix: /
Run Code Online (Sandbox Code Playgroud)
第三次测试:
肯定来自客户端的请求有问题,如果我使用类似的工具Postman并设置正确的标题我得到了我想要的实体,请参见下图:

我无法找到问题所在,所以我迫切需要某人的帮助,因为我已经没有想法了
Art*_*m L 24
正如大家建议的那样:只有Accept标头或扩展名可以给你一个JSON.好像你已经用Accept标头对它进行了排序.
为了使用扩展,你必须告诉你如何在Symfony中设置格式.
此代码应该为您提供所需的输出:
namespace RestTestBundle\Controller;
use FOS\RestBundle\Controller\Annotations\View;
use FOS\RestBundle\Controller\Annotations\Get;
class YourController
{
/**
* @Get("/api/v1/reps.{_format}", defaults={"_format"="json"})
* @View()
*/
public function indexAction()
{
return array(
'status' => 'ok',
'companies' => array(
array('id' => 5),
array('id' => 7),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
Edit1:如果你不想使用View类,但是纯数组:不要忘记禁止查看SensioExtraBundle的处理
sensio_framework_extra:
view: { annotations: false }
Run Code Online (Sandbox Code Playgroud)
Edit2:如果你不使用HTML格式并且只想拥有一个json输出,你可以使用这样的配置:
fos_rest:
# ....
format_listener:
rules:
- { path: ^/, priorities: [ json ], fallback_format: json, prefer_extension: true }
# ....
Run Code Online (Sandbox Code Playgroud)
解释为什么您看到错误"未找到视图":
TL; DR:您的浏览器发送一个Accept标头,告诉FOSRestBundle输出'html'变体.
背景:此捆绑包主要使用Accept头,这是一个很好的做法,可以使用所有可用的输出格式:html(您可以使用您提供的表单测试REST API,对象列表,对象的详细信息),json ,xml.有时甚至图像mime类型如image/jpeg,image/png作为默认值或json/xml作为变体(您可以使用base64图像表示).
说明:如果打开浏览器的"网络"选项卡并检查它发送的标题,您会注意到:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8这意味着"按此顺序使用":
如果您仔细观察,您会看到根据您的配置文本/ html是您的配置变体之一('html')和*/*是另一个变体('json'),但text/html有一个变体优先级为1,而*/*的优先级为0.8,因此text/html匹配,FOSRestBundle尝试查找HTML表示并失败.
PS:如果你多次发帖 - 请确保你注意每个帖子中的所有回复.
| 归档时间: |
|
| 查看次数: |
12095 次 |
| 最近记录: |