如何连接code主义实体JSON在Symfony的2.0 AJAX应用程序? [英] How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

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

问题描述

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

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

和我所有的控制器做同样的事情:得到一个实体和连接code它的一些领域JSON的。我知道,我可以使用正规化和连接code所有entitities。但是,如果一个实体循环链接到其他实体?还是实体图是非常大的?你有什么建议吗?

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?

我思考一些编码架构实体...或使用 NormalizableInterface 来避免骑自行车......

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

推荐答案

另一种方法是使用<一个href="https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Resources/doc/index.rst">JMSSerializerBundle.在你的控制器,你那么做的。

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;

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

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