使用 Symfony2 的网络服务
web services with Symfony2
我尝试在我的 Symfony2 项目中编写将提供 JSON 数据的 Web 服务。
我定义了路由来选择将处理来自 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),一切正常。
但在响应中我得到一个空 json:
{"products":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
有帮助吗?谢谢
这是因为您的 $products
是实体数组,而 php 不知道如何将 entity
序列化为 json。您需要将 getAll()
更改为:
$repository = $em->getRepository('ProductsBundle:Products');
$products = $repository->createQueryBuilder('p')
->getQuery()
->getArrayResult();
这将使您的 $products
普通数组可以被 json_encode
函数序列化。
见我的answer类似案例
我尝试在我的 Symfony2 项目中编写将提供 JSON 数据的 Web 服务。
我定义了路由来选择将处理来自 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),一切正常。
但在响应中我得到一个空 json:
{"products":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
有帮助吗?谢谢
这是因为您的 $products
是实体数组,而 php 不知道如何将 entity
序列化为 json。您需要将 getAll()
更改为:
$repository = $em->getRepository('ProductsBundle:Products');
$products = $repository->createQueryBuilder('p')
->getQuery()
->getArrayResult();
这将使您的 $products
普通数组可以被 json_encode
函数序列化。
见我的answer类似案例