使用API平台的序列化组件Symfony Serializer来返回深层级联数据。
代码示例:
namespace App\Serializer;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\JsonLd\Serializer\ContextTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
/**
* A custom serializer that can handle deep association data.
*/
class CustomSerializer extends Serializer
{
use ContextTrait;
public function __construct(
iterable $normalizers = [],
iterable $encoders = []
) {
$normalizers = array_merge($normalizers, [
// Doctrine paginator normalizer
new class() implements DenormalizerInterface {
public function denormalize($data, $class, $format = null, array $context = []) : Paginator
{
return Paginator::createFromCollection($data['data'], $data['totalItems'], $context['filters']['page'], $context['filters']['itemsPerPage']);
}
public function supportsDenormalization($data, $type, $format = null)
{
return $type === Paginator::class && $format === 'jsonapi';
}
},
// Object normalizer
new ObjectNormalizer(null, null, null, null, null, null, $this->extractAttributesToSerialize([])),
]);
parent::__construct($normalizers, $encoders);
}
/**
* @param string $data
* @param string $type
* @param string $format
* @param array $context
* @return object
* @throws InvalidArgumentException
*/
public function deserialize($data, $type, $format = null, array $context = [])
{
if (strpos($format ?? '', 'json') !== false) {
$data = $this->decode($data, $format);
}
return parent::deserialize($data, $type, $format, $this->createContext($format, $context));
}
/**
* @param mixed $data
* @param string $format
* @param array $context
* @return string
* @throws InvalidArgumentException
*/
public function serialize($data, $format = null, array $context = [])
{
$context += ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS];
$context = $this->createContext($format, $context);
$context['ignored_attributes'] = $this->extractAttributesToSerialize($
上一篇:API平台React生成器的问题
下一篇:API平台上的实体未显示