在symfony3中使用Unirest序列化数据

时间:2017-05-24 16:26:47

标签: php serialization postman symfony-3.2 unirest

我想通过查询搜索我的。我的服务器端工作一切都没问题。我在邮递员中验证了链接/人物/查询当我添加时当然运行良好吗?name = aaa效果很好。但问题出在我的symfony代码中,当我点击搜索按钮时,它给了我所有人的列表,如果什么都没有工作,所以我在转储变量后发现问题是我的变量体使用我试图改变它,但它不起作用。这是我的代码:

PersonController.php

  public function listAction(Request $request) {

    $serializer = new Serializer(
      array(new GetSetMethodNormalizer(), new ArrayDenormalizer()),
      array(new JsonEncoder())
    );
    $headers = array('Accept' => 'application/json');
    $response = Unirest\Request::get(link/persons/',$headers);
    $person = $serializer->deserialize($response->raw_body,
     Person::class, 'json');
    $form = $this->createForm(PersonType::class, $person);

    if ($request->isMethod('POST')) {
      $form->handleRequest($request);
      $headers = array('Accept' => 'application/json');
      //$body = json_encode($person);
      $body = Unirest\Request\Body::multipart($person);
      //$body = serialize($person);
      dump($body);
      $response = Unirest\Request::get('link/persons/query',
      $headers,$body);
      //$response = Unirest\Request::get('link/persons
      // /query?firstName=aaa'); (this works well)
      dump($response->body);
        return $this->render('AppBundle:Person:PersonList.html.twig',
      array (
            'form' => $form->createView(),
            'persons' => $response->body,
            ) );
    }

    $response = Unirest\Request::get('link/persons/',$headers);
    //$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
    if ($response->body == null) {
      return $this->render('AppBundle:Person:PersonList.html.twig', 
         array (
           'form' => $form->createView(),
           'persons' => $response->body,
           ) );
    }

    return $this->render('AppBundle:Person:PersonList.html.twig',
     array (
         'form' => $form->createView(),
         'persons' => $response->body,
         ) );
   }

否则,这是我的文件 Person.html / Twig

中有趣的部分
<form novalidate="novalidate" method="post">
    {{ form_row(form.name) }}
    {{ form_rest(form) }}
    <div class="form-group col-md-offset-5">
        <button type="submit" class="btn btn-default">Search</button>
    </div>
</form>

因此,当我点击“搜索”时,会执行“listAction”功能,但问题恰恰在于我的 $ body 不是好的。

1 个答案:

答案 0 :(得分:0)

最后,我找到了答案。我不得不序列化和反序列化我的数据。所以我只需要替换:

$body =  $serializer->serialize($person, 'json');

人:

$var =  $serializer->serialize($person, 'json');
$body = Json_decode($var , true);

问题是我没有将我的JSON转换为 Json_decode 函数所做的数组。