4

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

enter image description here

1

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

and with symfony 3, you can use return $this->json($restresult)
Now another error has appeared. Unable to find template "" (looked into: C:\xampp\htdocs\my_project_name\app/Resources/views, C:\xampp\htdocs\my_project_name\vendor\symfony\symfony\src\Symfony\Bridge\Twig/Resources/views/Form).
3

Repository method findAll returns array of objects. When you use json_encode on object with private properties, it returns {}, unless you implement JsonSerialize interface.

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.