FOSRestBundle json解码问题

时间:2012-11-22 08:52:33

标签: rest symfony fosrestbundle

使用FOSRestbundle,尝试使用POST将内容类型插入表中,并将内容类型设置为application/json。我的config.yml有以下

fos_rest:
  param_fetcher_listener: true
  body_listener: true
  format_listener:
    default_priorities: ['json', html, '*/*']
    prefer_extension: true
  view:
    view_response_listener: force
    failed_validation: HTTP_BAD_REQUEST
    default_engine: php
  formats:
    json: true

在控制器中添加了类似的东西

$request= $this->getRequest();
$form->bindRequest($request);
$em = $this->get('doctrine')->getEntityManager();
$em->persist($entity);
$em->flush();

但是获取所有数据库字段的null值。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

FOSRestBundle的Body Listener已经json解码请求内容并将其存储在Request参数包中。您可以使用

访问json解码数组

$request->request->all()

public function postFooAction(Request $request)
{
    if (!$request->getFormat($request->headers->get('Content-Type')) == 'json') {
        throw new BadRequestHttpException("Invalid Content-Type Headers");
    }
    $data = $request->request->all(); // FOSRestBundle's BodyListener sets the Request Parameter Bag to the json decoded data already



    return true;
}

答案 1 :(得分:1)

虽然它是Silex量身定制的,this应该可以解决您的问题:

use Symfony\Component\HttpFoundation\Request;

...

if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());
}

答案 2 :(得分:0)

Formtype getName方法返回formtype name,将其更改为表名。它现在正在工作。感谢。