Reputation: 41
I am a beginner in PHP & Symfony 3 and I have a problem: json_encode returns empty objects. You can check the image and code below.
/**
* @Rest\Get("/user")
*/
public function getAction()
{
$restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
return new Response(json_encode($restresult), Response::HTTP_OK);
}
Upvotes: 4
Views: 4146
Reputation: 1389
I think It's because the findAll() method return an array of object, you should personalize your method in the repository to get an array result,
public function findAllArray()
{
$qb = $this
->createQueryBuilder('u')
->select('u');
return $qb->getQuery()->getArrayResult();
}
Another thing, in Symfony you can use New JsonResponse to send Json datas
return new JsonResponse($restresult);
Upvotes: 6
Reputation: 4244
Repository method findAll
returns array of objects. When you use json_encode
on object with private properties, it returns {}
, unless you implement JsonSerialize
interface.
Upvotes: 3