简体   繁体   中英

Empty JSON Return - Symfony3

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

在此处输入图片说明

I think It's beacause 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);

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

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