Hassan Sardar
Hassan Sardar

Reputation: 4523

How to Encode JSON array in Doctrine?

How can I convert an Array into JSON in Doctrine ?

So far I have tried this.Here is my code:

require_once ("../Users.php");
require_once("../../test/doctrine/cli-config.php");
require_once "../../test/doctrine/bootstrap.php";

            $user_list = array();

            $usersRepository = $entityManager->getRepository('Users');

            $users = $usersRepository->findAll();  

            echo "<pre>";
            print_r($users);

            foreach ($users as $user) 
            {
                $user_list[] = array('user_list'=>$user);   
            }


  json_encode($user_list)

The print_r() section is returning me this:

Array
(
    [0] => Users Object
        (
            [id:Users:private] => 1
            [lastName:Users:private] => User1
            [firstName:Users:private] => Test1
            [city:Users:private] => ABC
            [country:Users:private] => XYZ
            [email:Users:private] => [email protected]
        )

    [1] => Users Object
        (
            [id:Users:private] => 2
            [lastName:Users:private] => User2
            [firstName:Users:private] => Test1
            [city:Users:private] => ABC
            [country:Users:private] => XYZ
            [email:Users:private] => [email protected]
        )

)
[{"user_list":{}},{"user_list":{}}]

See the Json Response is Empty. Can anyone help me with that?

Upvotes: 3

Views: 2605

Answers (1)

Udan
Udan

Reputation: 5609

You do not have public properties in your entities... that's why you get an empty json.

I am using for this purpose EntitySerializer

Usage for your case should be:

$eSerializer = new Bgy\Doctrine\EntitySerializer($entityManager);
$result = $eSerializer->toArray($users);

but this is just a personal preference. You could an should use the standard Serializer class of Symfony framework

Upvotes: 4

Related Questions