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

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

问题描述

我正在开发游戏应用程序并使用 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');
    }
}

我所有的控制器都做同样的事情:获取一个实体并将其中的一些字段编码为 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?

我考虑了一些实体的编码模式......或者使用 NormalizableInterface 来避免循环......,

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

推荐答案

另一种选择是使用 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:

 /**
* IddpRorBundleEntityReport
*
* @ORMTable()
* @ORMEntity(repositoryClass="IddpRorBundleEntityReportRepository")
* @ExclusionPolicy("None")
*/
....
/**
* @ORMManyToOne(targetEntity="Client", inversedBy="reports")
* @ORMJoinColumn(name="client_id", referencedColumnName="id")
* @Exclude
*/
protected $client;

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

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