在symfony中JsonResponse是一个生成Json响应的便捷方式。但是当我们将findAll查询出来的结果放入到JsonResponse时,他输出的Json数据居然为空。
1 |
[{},{},{}....] |
什么情况?呢
其实是我们的entity类的属性为私有化的问题。解决起来也很简单,就是修改我们相关的entity类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
namespace AppBundle\Entity; .... class XXXXXXX implements JsonSerializable { private $id; private $title; private $content; .... public function jsonSerialize() { return array( 'id'=> $this->id, 'title' => $this->title, 'content' => $this->content, ); } } |
核心就是实现JsonSerializable的jsonSerialize()方法,返回需要的属性为一个数组。
我们在controller中测试一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public function indexAction(Request $request) { $em=$this->getDoctrine()->getManager(); $entities=$em->getRepository('AppBundle:XXXXXXXXX')->findAll(); $response = new JsonResponse(); $response->headers->set('Content-Type', 'application/json'); $response->headers->set('Access-Control-Allow-Origin', '*'); $response->setEncodingOptions(JSON_UNESCAPED_UNICODE); $response->setData($entities); return $response; } |
其中有一行
$response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
此句话是用来处理JSON 编码,如果没有此句,你输出的Json数据很可能出现如下状况:
{\u0022id\u0022:1,\u0022iam\u0022:1
setEncodingOptions相关参数请查看:http://php.net/manual/zh/json.constants.php