Reputation: 361
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
Upvotes: 0
Views: 46
Reputation: 10910
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
Upvotes: 1