我有扩展FosRestController的控制器。如何从序列化返回正常结果?
现在来自jsonp return
functionName([{},{},{},{},{},{},{},{},{},{},{},{}]);
现在来自json return
[{"id":1,"title":"\u053f\u0565\u0576\u057f\u0580\u0578\u0576"},{"id":11,"title":"\u0546\u0578\u0580\u0584-\u0544\u0561\u0580\u0561\u0577"}]
这是我的行动
/**
* This function is used to get all Districts.
*
* @ApiDoc(
* resource=true,
* section="District",
* description="This function is used to get all Districts",
* statusCodes={
* 200="Returned when successful",
* 404="Returned when the Districts is empty"
* }
* )
*
* @return mixed
* @Rest\View(serializerGroups={"main"})
*/
public function cgetAction(Request $request)
{
// for jsonP
$callback = $this->get('request')->get('callback');
$em = $this->getDoctrine()->getManager();
$districts = $em->getRepository(self::ENTITY)->findAll();
if(!is_null($request->getRequestFormat()) && !is_null($callback))
{
$response = new JsonResponse($districts, 200, array());
$response->setCallback($callback);
return $response;
}
else
{
return $districts;
}
}
答案 0 :(得分:0)
你必须通过以下方式构建json:
$response = new JsonResponse(array_map(function($obj) {
return array('id' => $obj->getId(), 'title' => $obj->getTitle());
}, $districts), 200, array());