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

时间:2020-02-14 13:39:49

标签: api symfony json-ld api-platform.com hydration


我正在使用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;

    }

...

1 个答案:

答案 0 :(得分:1)

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

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

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