【问题标题】:How to get objects in JsonModel output RESTful API如何在 JsonModel 输出 RESTful API 中获取对象
【发布时间】:2016-01-20 12:19:47
【问题描述】:

这段代码运行良好:

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":[{},{},{},{},{},{},{},{}]}

【问题讨论】:

    标签: php orm doctrine-orm zend-framework2


    【解决方案1】:

    如果您只是将 Album 对象嵌入到这样的数组中,您将永远无法获得有效的 json 输出...
    JsonModel 类将无法将它们转换/序列化为有效的 json 数据,这就是您为每个 Album 获得 {}(一个空对象)的原因。

    要么在 Album 类中实现 JsonSerializable 接口,包括所需的代码在 jsonSerialize 方法中,要么转换为 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
        );
    );
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      相关资源
      最近更新 更多