json - 问题尝试将实体编码为 json

标签 json serialization entity symfony-2.3

我尝试将 Doctrine 实体编码为 JSON 字符串,以作为 Ajax 响应发送。 所以,我查看了文档:The Serializer Component

我尝试使用这段代码:

$em = $this->getDoctrine()->getManager();
// Get the entities repository
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();

// Instance the object
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));

// Convert only an item
foreach($sesiones_registradas as $sesion){
    echo $serializer->normalize($sesion,'json');
    break;
}
// Stop script
die();

最后的代码,失败说:

Could not normalize object of type AppsManantiales\AuditBundle\Entity\AuditSession, no supporting normalizer found.

如果将 $serializer->normalize($sesion,'json') 更改为 $serializer->serialize($sesion, 'json'); 则错误消息是:

Serialization for the format json is not supported

有什么想法吗?

最佳答案

您的问题来自您反转 normalizersencoders 的事实。

线路:
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
必须是:
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));

关于json - 问题尝试将实体编码为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953802/

相关文章:

WCF - 将空元素转换为可为空的 native 类型

entity-framework - Entity Framework 中的 FunctionImport 4 问题

javascript - 通过 api 调用 Json 与 HTML?

json - Elasticsearch-如何刷新http://<host>:port/heartbeat-*/_ search中的数据?

java - 为什么大多数Java框架的类都扩展了可序列化接口(interface)?

.net - 如何控制.NET DataContract序列化,使其使用XML属性而不是元素?

entity-framework - Entity Framework : add property that don't map to database

entity - DDD 中的一切都是值对象

javascript - 在 jQuery 中解析 JSON 对象

javascript - json数据未显示在js生成的表中