Symfony2 json回应

时间:2012-10-02 21:57:59

标签: json mongodb symfony

我在使用以下代码时遇到问题

/** @Route("/{collection}/{id}", name="object", defaults={"_format" = "json"}) */
public function retrieveOne($collection, $id)
{
    $collection = Inflector::classify($collection);

    $object = $this->get('doctrine_mongodb.odm.document_manager')
        ->getRepository('NameBundle:' . $collection)
        ->find($id);

    $response = new Response(json_encode($object));

    return $response;
}

文档

use Doctrine\ODM\MongoDB\Mapping\Annotations as Mongo;

/**
* Entrada
*
* @Mongo\Document
*/
class Entrada
{
    /**
     * @Mongo\Id
     */
    protected $id;

    /**
     * @Mongo\String
     * @var int $type
     */
    private $type;

    /**
     * @Mongo\String
     * @var string $nombre
     */
    private $nombre;

   //.. setters and getters
}

并且我总是在响应正文中得到{}

注意:查询正确返回对象

1 个答案:

答案 0 :(得分:2)

json_encode只会对公共属性进行编码。

所以你可以:

  • 公开你的财产(baaahhhh)
  • 在您的Entrada类上创建一个toArray()方法,然后执行json_encode($object->toArray())
  • 使用真棒JMSSerializerBundle
相关问题