如何在Json ld上下文中重命名@id-API平台[已解决]

问题描述 投票:0回答:1

我正在使用API​​,而我的Json-ld有问题是否可以在Json-ld上下文中更改@id?

实体:

/**
 * @ApiResource(
 *      normalizationContext={"groups"={"question_get"}},
 *      denormalizationContext={"groups"={"question_post"}},
 *      itemOperations={
 *          "get" = {
 *              "enable_max_depth"=true,
 *              "force_eager"=false,
 *          },
 *          "put" = {
 *               "denormalization_context"={"groups"={"question_put"}}
 *          }
 *      },
 *      collectionOperations={
 *          "get"= {
 *                   "normalization_context"={"groups"={"questions_get"}},
 *               },
 *          "post"
 *      },
 *      attributes={
 *          "enable_max_depth"="true",
 *          "pagination_client_items_per_page"=true,
 *      },
 *  )
 */
class Question
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

  ...

Json:

"@context": "/api/contexts/Question",
  "@id": "/api/questions",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/questions/32",
      "@type": "Question",
      "id": 32,
     ...

以及我想要的是:

  "@id": "/questions"

我想保留路径“ / api / question”,我只想更改实体的@id,而不是关系。

编辑:我找到了一种方法,我使用规范化器:https://api-platform.com/docs/core/identifiers/#custom-identifier-normalizer

#App\src\Serializer\ApiNormalizer.php

...

 public function normalize($object, $format = null, array $context = [])
    {

        $data = $this->decorated->normalize($object, $format, $context);

        $data['@id'] = substr($data['@id'], 4);

        return $data;

    }

...

api symfony json-ld api-platform.com hydration
1个回答
0
投票

您可以在上下文中提供别名/缩写:

"type" : "@type",
"id" :"@id"

这可让您摆脱文档和代码中的@符号。 read more

© www.soinside.com 2019 - 2024. All rights reserved.