how to convert a json to a php object in symfony2?
Via jquery, I ajax/POST this json
{"indices":[1,2,6]}:
to a symfony2 action. Right now I only really care for the array, so if this makes things considerably easier I could just post [1,2,6] as well.
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 f开发者_JAVA百科unction applySortIndexAction()
{
$request = $this->getRequest();
$j = json_decode($request->request->get('json'));
$indices = $j->indices;
return array('data'=> $indices);
}
gives a
Notice: Trying to get property of non-object in .../PageController.php line 64 (500 Internal Server Error)
which would be where I access $j->indices, where $j seems to be null
The poster:
$.ajax({
type: 'POST',
url: "{{ path('page_applysortindex')}}",
data: $.toJSON({indices: newOrder}),
success: ...
To get the data sent via body use:
$request = $this->getRequest();
$request->getContent();
inspect the output and then act upon. but this will contain the json.
(yep, tested it. this leads to your json)
getting a POST-parameter with name json from within a 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)
}
}
精彩评论