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

Time:05-01

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.

/**
 * @MongoDB\Document
 */
class User
{
   /**
    * @MongoDB\Id
    */
   protected $_id;
   /**
    * @MongoDB\Field(type="string")
    */
   protected $email;

   /**
    * @MongoDB\Field(type="string")
    */
   protected $password;

   /**
    * @MongoDB\Field(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.

CodePudding user response:

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:

/**
 * @MongoDB\Document
 */
class User implements JsonSerializable
{
    /**
     * @MongoDB\Id
     */
    protected $_id;
    /**
     * @MongoDB\Field(type="string")
     */
    protected $email;

    /**
     * @MongoDB\Field(type="string")
     */
    protected $password;

    /**
     * @MongoDB\Field(type="string")
     */
    protected $role;

    public function jsonSerialize() {
        return [
            '_id' => $this->_id,
            'email' => $this->email,
            'password' => $this->password,
            'role' => $this->role,
        ];
    }
}
  • Related