当作为 JsonResponse 返回时,从集合 returns 数组中查找所有具有空对象的对象
find all from collection returns array with empty objects when returned as a JsonResponse
所以,我是 symfony 的新手,需要在其中为大学项目创建一个 api。通常我会学习一些教程,但我没有时间正确学习 symfony,我们只教了基础知识。
我有一个包含姓名、电子邮件、密码的用户集合,我想 return 全部作为 json 的文档。这只是一个测试,不会用于最终项目,用户集合是最简单的,这就是我使用它的原因。
/**
* @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;
}
我在用户内部有 3 个文档。当我对使用 findall() 选择的数据 return 进行 dd(转储和死亡)时,我得到了数据。但是当我 return 获取用户的新 JsonResponse 时,我得到 [{},{},{}]。集合为空。
/**
* @Route("/api/users", name="users")
*/
public function test(DocumentManager $dm): Response
{
$repository = $dm->getRepository(User::class);
$Users = $repository->findAll();
return new JsonResponse($Users);
}
我是不是漏了一步?
提前致谢。
这与 Symfony 或 MongoDB 无关。关于纯PHP.
JsonResponse
将在您的对象上使用 json_encode
函数,该函数不会看到任何 public 属性,因此不会序列化任何内容。
要使用 json_encode
序列化您的数据,您应该使您的属性 public(不是 OOP 的正确方法)或实现 JsonSerializable
接口添加 public 方法 jsonSerialize
到你的 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,
];
}
}
所以,我是 symfony 的新手,需要在其中为大学项目创建一个 api。通常我会学习一些教程,但我没有时间正确学习 symfony,我们只教了基础知识。
我有一个包含姓名、电子邮件、密码的用户集合,我想 return 全部作为 json 的文档。这只是一个测试,不会用于最终项目,用户集合是最简单的,这就是我使用它的原因。
/**
* @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;
}
我在用户内部有 3 个文档。当我对使用 findall() 选择的数据 return 进行 dd(转储和死亡)时,我得到了数据。但是当我 return 获取用户的新 JsonResponse 时,我得到 [{},{},{}]。集合为空。
/**
* @Route("/api/users", name="users")
*/
public function test(DocumentManager $dm): Response
{
$repository = $dm->getRepository(User::class);
$Users = $repository->findAll();
return new JsonResponse($Users);
}
我是不是漏了一步?
提前致谢。
这与 Symfony 或 MongoDB 无关。关于纯PHP.
JsonResponse
将在您的对象上使用 json_encode
函数,该函数不会看到任何 public 属性,因此不会序列化任何内容。
要使用 json_encode
序列化您的数据,您应该使您的属性 public(不是 OOP 的正确方法)或实现 JsonSerializable
接口添加 public 方法 jsonSerialize
到你的 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,
];
}
}