我想将数据库表序列化为 json 文件:
$table = $this->em->getRepository($EntityName)->findAll();
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(array('datetime_format' => 'd.m.Y')), new ObjectNormalizer($classMetadataFactory)];
$serializer = new Serializer($normalizers, $encoders);
$context = [
'circular_reference_handler' => function ($object) {
return $object->getId();
},
'circular_reference_limit' => 0,
];
$data = $serializer->serialize($table, 'json', $context);
但我在性能上有一些问题。我的页面加载速度非常慢,几秒钟,然后我得到一个空白页。
我用它来序列化我的对象并发送 JsonResponse
<?php
namespace AppServicesApiSerializer;
use SymfonyComponentSerializerSerializer;
use SymfonyComponentSerializerNormalizerObjectNormalizer;
use SymfonyComponentSerializerNormalizerDateTimeNormalizer;
use SymfonyComponentSerializerNormalizerAbstractNormalizer;
use SymfonyComponentSerializerMappingLoaderAnnotationLoader;
use SymfonyComponentSerializerMappingFactoryClassMetadataFactory;
use DoctrineCommonAnnotationsAnnotationReader;
class ObjectSerializer
{
private $object;
private $specifics_attributes;
public function __construct($object, Array $groups = ['default'], Array $specifics_attributes = null)
{
$this->object = $object;
$this->groups = $groups;
$this->specifics_attributes = $specifics_attributes;
}
public function serializeObject(): ?Array
{
$object = $this->object;
$defaultContext = [
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
return $object;
},
];
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = [new DateTimeNormalizer('Y-m-d'), new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext)];
$serializer = new Serializer($normalizer);
return $serializer->normalize($object, null, $this->normalizerFilters());
}
private function normalizerFilters():Array
{
$groups = $this->groups;
$specifics_attributes = $this->specifics_attributes;
$normalizer_filter = [
'groups' => $groups,
];
if ($specifics_attributes) {
$normalizer_filter['attributes'] = $specifics_attributes;
}
return $normalizer_filter;
}
}
然后在控制器或其他服务中,我们可以像这样使用它
use AppServicesApiSerializerObjectSerializer;
/* Some codes */
$objectSerializer = new ObjectSerializer($objects, ['my_custom_attributes_groupe']);
return new JsonResponse([
'status' => 'success',
'MyEntityName' => $objectSerializer->serializeObject(),
], JsonResponse::HTTP_OK);