Want to return data in Json format by getting from database Object. Php Symfony

Viewed 44

I am getting data from database model and want to return in json format, but it returns empty array, but when i use dump for variable that contains objects data then it return the actual data.

Here is the code for getting data from object

   $user = $this->getUser();
    $bookings = $this->getDoctrine()->getRepository(Trip::class)
                ->findBy(['customer' => $user], ['id' => 'DESC']);

here i return it in json form

 return new JsonResponse(['bookings' => $bookings]);

It display on screen that array is empty.

enter image description here

i use dd to check whether data is comming or not

  $user = $this->getUser();
    $bookings = $this->getDoctrine()->getRepository(Trip::class)
                ->findBy(['customer' => $user], ['id' => 'DESC']);
     dd($bookings);

It returns

enter image description here

enter image description here

kindly help me out how to overcome this issue

2 Answers

You could use symfony component Serializer

You could either turn your array of objects into an array of array:

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), new ObjectNormalizer(
            null,
            null,
            null,
            new ReflectionExtractor()
        ),],[ new JsonEncoder(),]);
$bookings = $this->getDoctrine()->getRepository(Trip::class)
                ->findBy(['customer' => $this->getUser()], ['id' => 'DESC']);
$array = $serializer->normalize($bookings, 'array');

Or you could directly get a json using the serialize method:

 $json= $serializer->serialize($bookings, 'json');

If your entity has circular references, you can look into the documentation to handle it.

One way would be to add a callback method on how to handle objects, but It would be better if you read the documentation because the solution can vary depending on your entity.

Yes is empty because json_encode supported array or object properties public, you can see here. So You must parse $bookings.

JsonResponse use json_encode you can see

Example:

$array = [];
$arrayBooking = [];

foreach ($bookings as $booking) {
    $arrayBooking['id'] = $booking->getId();
    $arrayBooking['toPlace'] = $booking->getToPlace();
    $array[] = $arrayBooking;
}

return new JsonResponse($array);

Or, You use Serializer symfony component, as above.

Related