作为一个简单的例子,我有一个具有以下字段的学说实体
id
name
description
Run Code Online (Sandbox Code Playgroud)
我正在使用JMSSerializerBundle并且它在大多数情况下运行良好,但是如果我想让序列化数据(Json)包含未完全映射到我的实体的内容怎么办?
例如,如果我只想返回描述的前 50 个字符并且我想将其称为short_description.
我尝试使用排除策略来@Expose公开方法,但这不受支持。
我需要经常与许多不同的实体一起做这种事情,我想知道是否有人可以提出一个很好的干净的方法来解决这个问题。
我已经阅读了整个文档,JMSSerializerBundle并在互联网上寻找解决方案,我可以想出一些解决方案,但生成的代码看起来有点脏。
我有一个实体,我想在我正在开发的 JSON API 中公开它,问题是在这个特定的控制器中,只有一个我不想公开的字段。有没有办法将其从控制器内的序列化中排除?
我知道我可以注释我的实体,以便序列化器仅传递该字段,但在所有其他情况下会发生什么?这确实是个例外。
jmsSerializer 编码 perisan(或阿拉伯)字符。
$serializer = $this->get('jms_serializer');
dump('test');
dump($serializer->serialize('test', 'json'));
dump('???');
dump($serializer->serialize('???', 'json')); // <<---
die();
Run Code Online (Sandbox Code Playgroud)
我怎样才能防止这种行为?
在"friendsofsymfony/rest-bundle": "~1.4",我们设置了 setSerializationContext 的"jms/serializer-bundle": "^1.1.0",上下文中,我们设置了 gropu 并启用了深度
return View::create()
->setStatusCode(200)
->setData($certificatesResponse)
->setSerializationContext(
SerializationContext::create()
->enableMaxDepthChecks()
->setGroups(array('certificates_by_parameters'))
);
Run Code Online (Sandbox Code Playgroud)
早期"friendsofsymfony/rest-bundle": "~1.4",我们有来自 RestBundle 的 View 类的这个函数
/**
* Sets the serialization context.
*
* @param SerializationContext $serializationContext
*
* @return View
*/
public function setSerializationContext(SerializationContext $serializationContext)
{
$this->serializationContext = $serializationContext;
return $this;
}
Run Code Online (Sandbox Code Playgroud)
在"friendsofsymfony/rest-bundle": "^2.0",我没有找到这个功能,如何在2.0版本中设置序列化上下文?
我正在尝试使用@Groups注释来序列化我的数据,但我只是收到一个空数组。
我试过@Serializer\Expose在我想显示的字段上使用,但随后它们随处可见而忽略了这些组。
从我读过的内容来看,我很确定我应该只需要使用@Groups注释,但我最终得到了这个(有两个计划实体):
{
"schedules": [
{},
{}
]
}
Run Code Online (Sandbox Code Playgroud)
它的工作方式似乎发生了变化,我找到了以前版本 FOSRestBundle 的示例,我只是无法将它们移植到新版本。
据我了解,您可以在序列化程序上下文中设置组并使用它来设置视图上下文,但我对此并不走运。
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md
View::setSerializationContext 和 View::getSerializationContext 已被删除。将 View::setContext 和 View::getContext 与新的 Context 类一起使用。
前:
Run Code Online (Sandbox Code Playgroud)use JMS\Serializer\SerializationContext; $view = new View(); $context = new SerializationContext(); $view->setSerializationContext($context); $context = $view->getSerializationContext();后:
Run Code Online (Sandbox Code Playgroud)use FOS\RestBundle\Context\Context; $view = new View(); $context = new Context(); $view->setContext($context); $context = $view->getContext();
我花了很长时间来解决所有这些问题,并且非常感谢任何帮助为我指明正确方向的帮助。
除了下面我试图use FOS\RestBundle\Controller\Annotations as Rest; 和
@Rest\View(serializerGroups({"schedule"})注释与控制器上,它有同样的效果,因为我看到现在(即无)。
调度控制器
use FOS\RestBundle\Context\Context;
class ScheduleController extends BaseController
{ …Run Code Online (Sandbox Code Playgroud)