【问题标题】:API Platform: normalization context ignored in nested objectsAPI 平台:嵌套对象中忽略的规范化上下文
【发布时间】:2021-09-24 11:40:56
【问题描述】:

我有一个这样的 API 资源实体:

/**
 * @ApiResource(
 *     collectionOperations={},
 *     itemOperations={"get"},
 *     normalizationContext={"groups"={"read"}},
 * )
 */
class A
{
    /**
     * @var array<B>
     * @Groups("read")
     */
    private array $b;

    // ...
}

属性的@Groups 注释有效,我只得到带有@Groups("read") 的注释。

但我有这样的嵌套对象:

class B
{
    /**
     * @var array<C>
     * @Groups("read")
     */
    private array $c;

    // ...
}

class C
{

    /**
     * @Groups("read")
     */
    private string $foo;

    private string $bar;

    // ...
}

B 中,@Groups 注释仍然受到尊重,但在C 中,我得到了所有属性,完全忽略了注释。

预期输出如下:

{
  "b": [
    {
      "c": [
        {
          "foo": "This should be public"
        }
      ]
    }
  ]
}

得到如下输出:

{
  "b": [
    {
      "c": [
        {
          "foo": "This should be public"
          "bar": "This should be private"
        }
      ]
    }
  ]
}

我需要做什么才能完成这项工作?

(如果重要,BC 都不是 @ApiResource,但 C 是 Doctrine @Entity。我为 A 使用自定义数据提供程序)

【问题讨论】:

    标签: php symfony serialization api-platform.com


    【解决方案1】:

    我找到了... C 实现了 JsonSerializable,出于其他原因,来自 jsonSerialize() 的 JSON 表示包含 foobar

    API 平台显然会利用它(如果存在)。学到了一些东西!

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 2020-05-06
      • 2019-09-04
      • 2021-08-20
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2018-03-02
      相关资源
      最近更新 更多