【问题标题】:web services with Symfony2Symfony2 的网络服务
【发布时间】:2015-02-27 11:19:50
【问题描述】:

我尝试在我的 Symfony2 项目中编写将提供 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),一切正常。

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

{"products":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}

一些帮助?谢谢

【问题讨论】:

  • 只是一个注释,但您可以使用methods: [GET] 而不是requirements._method: GET 设置所需的方法。

标签: php json symfony


【解决方案1】:

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

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

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

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

查看我的answer 以了解类似情况

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2011-09-15
    • 1970-01-01
    • 2018-02-05
    • 2015-02-11
    相关资源
    最近更新 更多