我正试图使用@Groups
注释来序列化我的数据,但我只是收到一个空数组。
我试过在我想显示的字段上使用@SerializerExpose
,但后来它们到处都显示,并忽略了组。
根据我所读到的内容,我很确定我应该只需要使用@Groups
注释,但我最终得到了这个(有两个调度实体):
{
"schedules": [
{},
{}
]
}
这似乎发生了变化,我发现了以前版本FOSRestBundle的例子,只是无法将它们移植到新版本。
据我所知,您可以在序列化程序上下文中设置组,并使用它来设置视图上下文,但我在这方面运气不佳。
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md
View::setSerializationContext和View::getSerializationContext。请将View::setContext和View::getContext与新的Context类一起使用。
之前:
use JMSSerializerSerializationContext; $view = new View(); $context = new SerializationContext(); $view->setSerializationContext($context); $context = $view->getSerializationContext();
之后:
use FOSRestBundleContextContext; $view = new View(); $context = new Context(); $view->setContext($context); $context = $view->getContext();
我很难理解这一切,如果能为我指明正确的方向,我将不胜感激。
除了以下内容外,我还尝试use FOSRestBundleControllerAnnotations as Rest;
和控制器上带有的@RestView(serializerGroups({"schedule"})
注释,其效果与我现在看到的效果相同(即无)。
调度控制器
use FOSRestBundleContextContext;
class ScheduleController extends BaseController
{
/**
* @param $date
* @return SymfonyComponentHttpFoundationResponse
*/
public function getSchedulesScheduleAction($date)
{
$em = $this->getDoctrine()->getManager();
list($startDate, $endDate) = $this->get('radio.utils.date_and_time')->findWeekRange($date);
$schedules = $em->getRepository('RadioBundle:Schedule')->findByRange($startDate, $endDate);
$view = $this->view(
[
'schedules' => $schedules,
],
200
);
$context = new Context();
$context->setGroups(["schedule"]);
$view->setContext($context);
return $this->handleView($view);
}
}
计划实体
use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
use JMSSerializerAnnotation as Serializer;
/**
* Schedule
*
* @ORMTable(name="schedule")
* @ORMEntity(repositoryClass="RadioBundleRepositoryScheduleRepository")
* @SerializerExclusionPolicy("all")
*/
class Schedule
{
/**
* @var int
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var DateTime
* @AssertNotBlank()
* @SerializerGroups({"schedule"})
* @ORMColumn(name="start_time", type="datetime")
*/
private $startTime;
/**
* @var DateTime
* @AssertNotBlank()
* @SerializerGroups({"schedule"})
* @ORMColumn(name="end_time", type="datetime")
*/
private $endTime;
/**
* @AssertNotBlank()
* @SerializerGroups({"schedule"})
* @ORMManyToOne(targetEntity="RadioBundleEntityRadioShow", inversedBy="schedule")
*/
private $radioShow;
...
app/config.yml
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
routing_loader:
default_format: json
jms_serializer:
metadata:
auto_detection: true
在实体上使用ExclusionPolicy("all")时,您需要向组公开属性。
例如
/**
* @var DateTime
* @AssertNotBlank()
* @SerializerGroups({"schedule"})
* @SerializerExpose()
* @ORMColumn(name="start_time", type="datetime")
*/
private $startTime;