val*_*epu 4 php rest symfony fosrestbundle jmsserializerbundle
我正在尝试使用Symfony 3和FOSRestBundle制作Rest Web服务。
我来自Spring + Jackson的背景,所以我正在努力做到这一点,以便您可以将对象作为请求主体传递给控制器,这些请求成为函数参数,并返回序列化为json的对象,到目前为止,我设法使其适用于一切除了数组。
这是我的代码:
组态:
#FOSRestBundle
fos_rest:
param_fetcher_listener: true
body_listener:
enabled: true
decoders:
json: fos_rest.decoder.json
format_listener:
rules:
- { path: ^/, priorities: [ json ], fallback_format: json, prefer_extension: true }
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)
这是控制器
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use JMS\DiExtraBundle\Annotation\Inject;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\View;
use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class DefaultController extends FOSRestController {
/**
* @Post("/rest", name="rest_test")
* @ParamConverter("myArr", converter="fos_rest.request_body")
* @View
* @param Request $request
*/
public function restAction(Request $request, array $myArr) {
return $myArr;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试从我的其余客户端([1, 2]作为请求正文)调用此方法时,我收到此错误:
{
"code": 500,
"message": "Converter 'fos_rest.request_body' does not support conversion of parameter 'myArr'."
}
Run Code Online (Sandbox Code Playgroud)
如果我myArr变成一个对象(即我将其类型从更改array为MyObject,包含number变量myVar)并发送反映该对象结构的数据(例如{"myVar": 2}),则效果很好,但不适用于数组。
经过数天的代码玩弄以及与FoS的合作者之一的愉快对话https://github.com/FriendsOfSymfony/FOSRestBundle/issues/1582我发现,如果您使用的是JMS Serializer Bundle(我认为每个人都有),您只需array在param转换器的class字段中进行编写,它将反序列化为数组。我猜我应该早点尝试一下
@ParamConverter("myarr", class="array", converter="fos_rest.request_body")
Run Code Online (Sandbox Code Playgroud)
它甚至可以反序列化对象数组(我想只要它们是同一类)
@ParamConverter("myarr", class="array<Namespace/Class>", converter="fos_rest.request_body")
Run Code Online (Sandbox Code Playgroud)
更新我正在更新此问题,因为我停止使用JMS序列化器并开始使用Symfony序列化器,对于对象数组它具有不同的语法:
@ParamConverter("myarr", class="Namespace/Class[]", converter="fos_rest.request_body")
Run Code Online (Sandbox Code Playgroud)
普通数组语法保持不变