如何在 JsonModel 输出 RESTful API 中获取对象


How to get objects in JsonModel output RESTful API

这段代码工作正常:

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
    );
);