How to convert json to php object in symfony2?

Via jquery, I ajax / POST this json

{"indices":[1,2,6]}: 

for symfony2 action. Right now, I only really care about the array, so if that makes it much easier, I could just post [1,2,6].

How can I convert this to a php object?


Somehow this does not work:

 /** * @Route("/admin/page/applySortIndex", name="page_applysortindex") * @Method("post") * @Template() */ public function applySortIndexAction() { $request = $this->getRequest(); $j = json_decode($request->request->get('json')); $indices = $j->indices; return array('data'=> $indices); } 

gives

Note: attempt to get non-object property in ... /PageController.php line 64 (500 Internal Server Error)

where I will access the indices $ j->, where $ j seems to be zero


Poster:

 $.ajax({ type: 'POST', url: "{{ path('page_applysortindex')}}", data: $.toJSON({indices: newOrder}), success: ... 
+6
source share
1 answer

To receive data sent using the body:

 $request = $this->getRequest(); $request->getContent(); 

check the conclusion and then act. but it will contain json.

(yep, tested it, this will result in your json)


getting a POST parameter named json from inside the controller:

 $request = $this->getRequest(); $request->request->get('json'); 

Request-object


 $j = json_decode('{"indices":[1,2,6]}'); var_dump($j); 

leads to:

 object(stdClass)#1 (1) { ["indices"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(6) } } 
+5
source

Source: https://habr.com/ru/post/896965/


All Articles