Json Symfony2学说与对策

Json Symfony2学说与对策,json,symfony,doctrine,Json,Symfony,Doctrine,我有一个小问题,我试图发送一个json响应,但我得到的总是一个空对象 这是我的代码: //Get the data from DB $template = $this->getDoctrine() ->getRepository('EVRYgroBundle:Template') ->findOneBy( array('active' => 1) ); if (!$template) { throw

我有一个小问题,我试图发送一个json响应,但我得到的总是一个空对象

这是我的代码:

//Get the data from DB
$template = $this->getDoctrine()
    ->getRepository('EVRYgroBundle:Template')
    ->findOneBy(
        array('active' => 1)
        );

    if (!$template) {
        throw $this->createNotFoundException(
            'No product found for id '
        );
    }

  //Send the response
 $response = new Response();
 $response->setContent(json_encode($template));
 return $response;
当我看到它时,它显示的是{} 我还尝试了jsonResponse和以下代码:

$response = new JsonResponse();
$response->setData($template);

我不知道我做错了什么

我发现了问题,问题是一些保存数据库信息的变量被设置为受保护而非公共。

json\u encode希望在中给出一个数组作为第一个参数。当您使用对象调用它时,可能会显示公共属性。要保持属性受保护(应如此),可以向实体添加公开函数:

/**
 * delivers all properties and values of the entity easily
 *
 * @return array
 */
public function expose()
{
    return get_object_vars($this);
}
然后打电话

$response->setData(json_encode($template->expose()));

通过这种方式,您只需通过getter和setter方法进行访问,就可以保持实体干净,并且仍然可以通过json访问所有属性。

您还没有所有的getter和setter吗?