1

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>&nbsp;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?
}"

为什么当我不使用注释时它会起作用?当我使用注释时,为什么日期和其他实体是空数组?

4

1 回答 1

0

尤里卡!

这是我的序列化方法的代码片段:

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([
    // Add a Datetimenormalizer as the first normalizer in the list
    new DatetimeNormalizer(),
    $normalizer
], [new JsonEncoder()]);

return $serializer->serialize($this, 'json', [
    // $serializer->addCircularReferenceHandler() IS DEPRECATED
    // define the handler like this:
    ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($event) {
        return '/event/'.$event->id;
    }
    ,ObjectNormalizer::GROUPS => $serializingGroups
]);

First of all, the reason why meta and targets weren't serializing was because I had the wrong import in my Meta and Target entities. Make sure it is: use Symfony\Component\Serializer\Annotation\Groups;... so... yeah... moving on.

The dates did serialize when I commented out //,ObjectNormalizer::GROUPS => $serializingGroups. So why don't they serialize when groups aren't commented out? My guess is that the DateTime class doesn't have the Groups annotations, so the normalizer was never able to get any of the DateTime attributes

This is solved by adding a DatetimeNormalizer as the first normalizer in the array: $serializer = new Serializer([new DatetimeNormalizer(),$normalizer])

This is how my entities serialize correctly :D

于 2019-02-10T20:33:58.313 回答