Php 使用FOSRestBundle(对象数组)返回正确的JSON
我有一个POST action,如下所示:Php 使用FOSRestBundle(对象数组)返回正确的JSON,php,json,fosrestbundle,Php,Json,Fosrestbundle,我有一个POST action,如下所示: public function cpostAction(Request $request) { $records = json_decode($request->getContent(), true); $arr = array(); $em = $this->getDoctrine()->getManager(); foreach((array)$records as $record) {
public function cpostAction(Request $request)
{
$records = json_decode($request->getContent(), true);
$arr = array();
$em = $this->getDoctrine()->getManager();
foreach((array)$records as $record) {
$obj = new \stdClass();
$entity = new Record();
$entity->setRouteId($record['routeId']);
$entity->setDate(new \DateTime('now'));
$entity->setUserId($record['userId']);
$entity->setSync($record['sync']);
$obj->id = $record['id'];
$em->persist($entity);
$em->flush();
$obj->remote_id = $entity->getId();
$obj = json_encode($obj, true);
array_push($arr, $obj);
}
$view = View::create();
$view->setFormat('json');
$view->setData($arr);
return $this->get('fos_rest.view_handler')->handle($view);
}
如果我保留$obj=json\u encode($obj,true)代码>,我得到了这个响应
[
"{\"id\":1,\"remote_id\":52}",
"{\"id\":2,\"remote_id\":53}",
"{\"id\":3,\"remote_id\":54}"
]
如果没有这行代码,我会
{
"0": {},
"1": {},
"2": {}
}
如何获取正确的JSON?如果使用数组而不是stdClass
,会怎么样?序列化程序只是不知道如何序列化给定的objects@zerkms:那很好用,谢谢!