使用Symfony2的Web服务

时间:2015-02-27 11:19:50

标签: php json symfony

我尝试在我的Symfony2项目中编写Web服务,该项目将提供JSON数据。

我定义了路由来选择将处理来自Web服务的请求和响应的控制器:

_api_v1__get_products:
pattern:  /v1/products/{_locale}.{_format}
defaults: { _controller: ProductsBundle:Api:products, _format: json, _locale: en-US}
requirements:
  _method:  GET

控制器:

    public function productsAction() {

    $em = $this->getDoctrine()->getManager();

    $repository = $em->getRepository('ProductsBundle:Products');

    $products = $repository->getAll();

    //var_dump($products); die;

    return new Response(json_encode(array('products' => $products)));
}

我查看了var_dump($ products),一切正常。

但在Response中我得到一个空的json:

{"products":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
有些帮助吗?感谢

1 个答案:

答案 0 :(得分:1)

这是因为你的$products是实体数组,php不知道如何将entity序列化为json。您需要将getAll()更改为:

$repository = $em->getRepository('ProductsBundle:Products');

$products = $repository->createQueryBuilder('p')
                ->getQuery()
                ->getArrayResult();

这将使您的$products普通数组可以通过json_encode函数进行序列化。

查看我的answer类似案例