Posting JSON objects to Symfony 2

后端 未结 3 888
广开言路
广开言路 2020-11-27 05:35

I\'m working on a project using Symfony 2, I\'ve built a bundle to handle all my database services which passes JSON data back and forward.

My Problem/Question:

3条回答
  •  独厮守ぢ
    2020-11-27 06:10

    I wrote method to get content as array

    protected function getContentAsArray(Request $request){
        $content = $request->getContent();
    
        if(empty($content)){
            throw new BadRequestHttpException("Content is empty");
        }
    
        if(!Validator::isValidJsonString($content)){
            throw new BadRequestHttpException("Content is not a valid json");
        }
    
        return new ArrayCollection(json_decode($content, true));
    }
    

    And I use this method as shown below

    $content = $this->getContentAsArray($request);
    $category = new Category();
    $category->setTitle($content->get('title'));
    $category->setMetaTitle($content->get('meta_title'));
    

提交回复
热议问题