Skip to content
Advertisement

find all from collection returns array with empty objects when returned as a JsonResponse

So, I am new to symfony and need to create an api in it for a project at college. Normally I would go through some tutorials, but I do not have the time to properly learn symfony and we were only taught the basics.

I have a collection of users containing name, email, password and I want to return all as documents as json. It’s just a test and won’t be used an the final project, the user collection is the simplest that’s why I’m using it.

/**
 * @MongoDBDocument
 */
class User
{
   /**
    * @MongoDBId
    */
   protected $_id;
   /**
    * @MongoDBField(type="string")
    */
   protected $email;

   /**
    * @MongoDBField(type="string")
    */
   protected $password;

   /**
    * @MongoDBField(type="string")
    */
   protected $role;
}

I have 3 documents inside users. When I’m doing a dd (dump and die) to return the data selected with a findall(), I get the data. But when I’m returning a new JsonResponse of users I get [{},{},{}]. The collections are empty.

/**
 * @Route("/api/users", name="users")
 */
public function test(DocumentManager $dm): Response
{
    $repository = $dm->getRepository(User::class);
    $Users = $repository->findAll();

    return new JsonResponse($Users);
}

Am I missing a step?

Thanks in advance.

Advertisement

Answer

It is not about Symfony or MongoDB. It is about pure PHP.

JsonResponse will use json_encode function on your object that will not see any public properties and so will do not serialize anything.

To serialize your data using json_encode you should either make your properties public (not the right way for OOP) or implement JsonSerializable interface adding public method jsonSerialize to your class:

/**
 * @MongoDBDocument
 */
class User implements JsonSerializable
{
    /**
     * @MongoDBId
     */
    protected $_id;
    /**
     * @MongoDBField(type="string")
     */
    protected $email;

    /**
     * @MongoDBField(type="string")
     */
    protected $password;

    /**
     * @MongoDBField(type="string")
     */
    protected $role;

    public function jsonSerialize() {
        return [
            '_id' => $this->_id,
            'email' => $this->email,
            'password' => $this->password,
            'role' => $this->role,
        ];
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement