[英]Serialize POST request body into array with FOSRestBundle
我正在嘗試使用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
這是控制器
<?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;
}
}
當我嘗試從我的休息客戶端調用此項(將[1, 2]
作為請求主體)時,我收到此錯誤:
{
"code": 500,
"message": "Converter 'fos_rest.request_body' does not support conversion of parameter 'myArr'."
}
如果我將myArr
轉換為一個對象(即我將其類型從array
更改為MyObject
,包含number
變量myVar
)並發送反映該對象結構的數據(例如{"myVar": 2}
),它可以正常工作,但它不適用於數組。
經過幾天玩弄代碼和與FoS的一個合作者的良好對話https://github.com/FriendsOfSymfony/FOSRestBundle/issues/1582我發現,如果你使用的是JMS Serializer Bundle(我認為每個人都有),您可以在param轉換器的類字段中編寫array
,並將其反序列化為數組。 我猜我應該早點嘗試過
@ParamConverter("myarr", class="array", converter="fos_rest.request_body")
它甚至可以反序列化對象數組(只要它們是同一個類,我猜)
@ParamConverter("myarr", class="array<Namespace/Class>", converter="fos_rest.request_body")
更新我正在更新這個問題,因為我停止使用JMS Serializer並開始使用Symfony Serializer,它具有不同的對象數組語法:
@ParamConverter("myarr", class="Namespace/Class[]", converter="fos_rest.request_body")
正常數組語法不受影響
FOS Rest體轉換器的目的是填充對象,而不是數組。 你可以嘗試實現自己的param轉換器( 參見本文檔 ),但我真的不確定你能達到你想要的效果。
無論如何,處理物體會不會更干凈? 它可以讓您確保您收到的數據符合您的預期,使用驗證等等......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.