How does symfony convert data read from findall to json?
$repository = $this->getDoctrine()->getRepository('AppBundle:User');$all = $repository->findAll();
array (size=2) 0 => object(AppBundle\Entity\User)[248] private 'id' => int 1 private 'name' => string 'A Foo Bar' (length=9) private 'pass' => string '19.99' (length=5) 1 => object(AppBundle\Entity\User)[251] private 'id' => int 2 private 'name' => string 'Two Fot Bar' (length=11) private 'pass' => string '40.00' (length=5)
The returned data is like this. how can we convert it to json data?
I now use return new JsonResponse ($ all); [{}]
Reply to discussion (solution)
You need to implement the JsonSerializable interface for AppBundle \ Entity \ User
For example
class T implements JsonSerializable { private $id; private $name; private $pass; function __construct($id, $name, $pass) { $this->id = $id; $this->name = $name; $this->pass = $pass; } function jsonSerialize() { return array( 'id' => $this->id, 'name' => $this->name, 'pass' => $this->pass, ); }}$d[] = new T(1, 'a', 'p');$d[] = new T(2, 'b', 'p');echo json_encode($d);
[{"Id": 1, "name": "a", "pass": "p" },{ "id": 2, "name": "B ", "pass": "p"}]
Otherwise, it can only be [{}, {}]
Because the returned property is private
You need to implement the JsonSerializable interface for AppBundle \ Entity \ User
For example
class T implements JsonSerializable { private $id; private $name; private $pass; function __construct($id, $name, $pass) { $this->id = $id; $this->name = $name; $this->pass = $pass; } function jsonSerialize() { return array( 'id' => $this->id, 'name' => $this->name, 'pass' => $this->pass, ); }}$d[] = new T(1, 'a', 'p');$d[] = new T(2, 'b', 'p');echo json_encode($d);
[{"Id": 1, "name": "a", "pass": "p" },{ "id": 2, "name": "B ", "pass": "p"}]
Otherwise, it can only be [{}, {}]
Because the returned property is private
Thanks, because the property is private.