简体   繁体   中英

web services with Symfony2

I try to write web services in my Symfony2 project that will provide JSON data.

I defined route to choose controller that will handle requests and responses from the web service:

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

The controller:

    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)));
}

I check with a var_dump($products), and everything works.

but in the Response i get an empty json:

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

some help? thanks

This is because your $products is array of entities and php doesn't know how to serialize entity to json. You need to change getAll() to something like:

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

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

This will make your $products plain array which will be serializable by json_encode function.

See my answer to similar case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM