drbmhd9583 2017-10-20 13:33
浏览 221

如何在symfony中正确处理JSON请求?

I'm trying to handle this problem: My app send JSON POST request with several information encoded in a Json. Example:

{"UserInfoA":{"1":123,"2":"hello","3":"bye","4":{"subinfo":1,"subinfo2":10}},
 "UserInfoB":{"a":"12345678","b":"asd"}} // and so on...

each UserInfo have:

  • Its own entity (although some request may have information of more than one entity).
  • A controller to persist this Object on DB and then give back the ID on this DB.

So, to achieve this problem I did another controller like JsonHandler, which receive this request and then forward to each controller after gut this JSON into differents objects. Example:

public function getJson (Request $request){
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
                $data = json_decode($request->getContent(), true);
            }
    if (!isset($data['UserInfoA'])){
         return new JsonResponse('ERROR');
              }
    $uia = $data['UserInfoA'];
    $idInfoA = $this->forward('Path::dataAPersist',array('data'=>$uia));
        }
    // same with userinfoB and other objects
    return $idInfoA ;

This works perfectly but Is it correct? Should i use services instead?

EDIT : I need to response the ID in a Json and this->forward returns a Response, so i can't use JsonResponse and if a send directly $idInfoA just send the IDNUMBER not in a JSON, how can i do it?

To sum up : a Json listener that receive the information, work it and then dispatch to the corresponding controller. This listener, should be a controller, a service or another thing?

  • 写回答

3条回答 默认 最新

  • dou7466 2017-10-20 16:04
    关注

    You can use symfony ParamConverter to to convert the json into any object you want and raise a meaningful Exception if anything goes wrong.

    You can add custom ParamConverters and use them in your actions with annotation

    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。