Symfony v4.2
我正在尝试使用 symfony 的规范化器和序列化器将我的实体转换为 JSON。
我遵循了 Groups 注释模式,因为这听起来是最直观和面向未来的方法。
根据文档,我们必须手动实例化ClassMetadataFactory
才能加载AnnotationLoader
. ObjectNormalizer
在使用注释之前,我仍在使用which 工作正常。
这是我的序列化方法:
/**
* @param bool $event Serialize all event fields (except references)
* @param bool $meta Serialize referenced meta instance
* @param bool $targets Serialize referenced target instances
* @param bool $users Serialize referenced user instances
* @param bool $videos Serialize referenced video instances
* @param bool $photos Serialize referenced photo instances
* @return string
*/
public function serialize($event = true, $meta = false, $targets = false, $users = false, $videos = false, $photos = false) {
$serializingGroups = [];
if ($event) {
$serializingGroups[] = 'event';
}
if ($meta) {
$serializingGroups[] = 'meta';
}
if ($targets) {
$serializingGroups[] = "targets";
}
if ($users) {
$serializingGroups[] = 'users';
}
if ($videos) {
$serializingGroups[] = 'videos';
}
if ($photos) {
$serializingGroups[] = 'photos';
}
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer], [new JsonEncoder()]);
$data = $serializer->normalize($this, null, ['groups' => $serializingGroups]);
return $serializer->serialize($data, 'json');
}
如果我不需要序列化关联,这些组可以加速序列化。
现在我使用了组注释,json 看起来像这样
"{"id":2,
"title":"test",
"description":"<p> test<\/p>",
"subscriptionPrice":"0.00",
"subscriptionUntil":[], // DATE - WHY EMPTY ARRAY?
"start":[], // DATE - WHY EMPTY ARRAY?
"end":[], // DATE - WHY EMPTY ARRAY?
"allDay":false,
"creationDate":[], // DATE - WHY EMPTY ARRAY?
"editDate":[], // DATE - WHY EMPTY ARRAY?
"editable":true,
"startEditable":true,
"durationEditable":true,
"overlap":false,
"color":"#9EABAB",
"backgroundColor":"#9eabab",
"borderColor":"#9eabab",
"textColor":"#000000",
"isRecurring":true,
"meta":[], // ASSOCIATED ENTITY - WHY EMPTY ARRAY?
"targets":[[]] // ASSOCIATED COLLECTION OF ENTITIES - WHY EMPTY ARRAY?
}"
为什么当我不使用注释时它会起作用?当我使用注释时,为什么日期和其他实体是空数组?