0

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

1
  • Just a note but you can set the required methods using methods: [GET] rather than requirements._method: GET. Commented Feb 27, 2015 at 11:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.