这段代码工作正常:
class AlbumController extends AbstractActionController
{
public function indexAction()
{
return new ViewModel(
array(
'albums' => $this->getEntityManager()->getRepository('Album'Entity'Album')->findAll()
)
);
}
}
此代码发送了空对象:
class AlbumController extends AbstractRestfulController
{
public function getList()
{
return new JsonModel(
array(
'albums' => $this->getEntityManager()->getRepository('Album'Entity'Album')->findAll()
)
);
}
}
//is returning result like this
{"albums":[{},{},{},{},{},{},{},{}]}
如果您只是将Album
对象嵌入到这样的数组中,您将永远不会获得有效的 json 输出......JsonModel
类将无法将它们转换/序列化为有效的 json 数据,这就是为什么您为每个Album
获得{}
(空对象)的原因。
要么在Album
类的jsonSerialize
方法中实现一个包含所需代码的JsonSerializable
接口,要么转换为JsonModel
知道如何序列化的东西,就像控制器方法中的数组一样。
JsonSerializable
:
class Album implements JsonSerializable {
// ...
function jsonSerialize() {
//some means of serializing the data...
}
}
或者只需在getList
方法的AlbumController
内手动执行此操作:
$albums = $this->getEntityManager()->getRepository('Album'Entity'Album')->findAll()
$array = [];
foreach( $albums as $album ){
$array[] = [
'id' => $album->getId(),
'name' => $album->getName()
]
}
return new JsonModel(
array(
'albums' => $array
);
);