在Symfony 2.0 AJAX应用程序中如何将Doctrine实体编码为JSON? [英] How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

查看:128
本文介绍了在Symfony 2.0 AJAX应用程序中如何将Doctrine实体编码为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发游戏应用程序并使用Symfony 2.0。我有很多AJAX请求到后端。而更多的反应是将实体转换为JSON。例如:

  class DefaultController extends Controller 
{
public function launchAction()
{
$ user = $ this-> getDoctrine()
- > getRepository('UserBundle:User')
- > find($ id);

//将用户编码为json格式
$ userDataAsJson = $ this-> encodeUserDataToJson($ user);
返回数组(
'userDataAsJson'=> $ userDataAsJson
);
}

私有函数encodeUserDataToJson(User $ user)
{
$ userData = array(
'id'=> $ user-> getId(),
'profile'=>数组(
'昵称'=> $ user-> getProfile() - > getNickname()

) ;

$ jsonEncoder = new JsonEncoder();
return $ jsonEncoder-> encode($ userData,$ format ='json');
}
}

我所有的控制器都做同样的事情:get a实体并将其一些字段编码为JSON。我知道我可以使用规范化器并编码所有的权限。但是,如果一个实体将链接循环到其他实体呢?还是实体图很大?你有什么建议吗?



我想一些实体的编码模式...或使用 NormalizableInterface 来避免循环.., p>

解决方案

另一个选项是使用 JMSSerializerBundle 。然后在控制器中执行

  $ serializer = $ this-> container-> get('serializer'); 
$ reports = $ serializer-> serialize($ doctrineobject,'json');
返回新回应($报告); //应为$ report as $ doctrineobject不序列化

您可以配置序列化如何完成在实体类中使用注释。请参阅上面链接中的文档。例如,以下是排除链接实体的方式:

  / ** 
* Iddp\RorBundle\Entity \Report
*
* @ ORM\Table()
* @ ORM\Entity(repositoryClass =Iddp\RorBundle\Entity\ReportRepository)
* @ExclusionPolicy(无)
* /
....
/ **
* @ ORM\ManyToOne(targetEntity =Client,inversedBy =reports )
* @ ORM\JoinColumn(name =client_id,referencedColumnName =id)
* @Exclude
* /
protected $ client;


I'm developing game app and using Symfony 2.0. I have many AJAX requests to the backend. And more responses is converting entity to JSON. For example:

class DefaultController extends Controller
{           
    public function launchAction()
    {   
        $user = $this->getDoctrine()
                     ->getRepository('UserBundle:User')                
                     ->find($id);

        // encode user to json format
        $userDataAsJson = $this->encodeUserDataToJson($user);
        return array(
            'userDataAsJson' => $userDataAsJson
        );            
    }

    private function encodeUserDataToJson(User $user)
    {
        $userData = array(
            'id' => $user->getId(),
            'profile' => array(
                'nickname' => $user->getProfile()->getNickname()
            )
        );

        $jsonEncoder = new JsonEncoder();        
        return $jsonEncoder->encode($userData, $format = 'json');
    }
}

And all my controllers do the same thing: get an entity and encode some of its fields to JSON. I know that I can use normalizers and encode all entitities. But what if an entity has cycled links to other entity? Or the entities graph is very big? Do you have any suggestions?

I think about some encoding schema for entities... or using NormalizableInterface to avoid cycling..,

解决方案

Another option is to use the JMSSerializerBundle. In your controller you then do

$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($doctrineobject, 'json');
return new Response($reports); // should be $reports as $doctrineobject is not serialized

You can configure how the serialization is done by using annotations in the entity class. See the documentation in the link above. For example, here's how you would exclude linked entities:

 /**
* Iddp\RorBundle\Entity\Report
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Iddp\RorBundle\Entity\ReportRepository")
* @ExclusionPolicy("None")
*/
....
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="reports")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
* @Exclude
*/
protected $client;

这篇关于在Symfony 2.0 AJAX应用程序中如何将Doctrine实体编码为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆