gpt4 book ai didi

json - 在 REST API 中索引数组集合元素

转载 作者:行者123 更新时间:2023-12-04 01:56:51 27 4
gpt4 key购买 nike

想象一下,我有一个数组集合 $items ,并实现了一个方法 removeItem在我的 SomeEntity实体类,

public function removeItem(Item $item)
{
$this->items->removeElement($item);
return $this;
}

以及接收 PATCH 请求的 Controller 操作:
public function patchAction(Request $request, SomeEntity $entity) {
$form = ...;

$form->handleRequest($request);
if ($form->isValid()) {
...
$this->get('doctrine.orm.entity_manager')->flush();

return $entity;
}

return $form;
}

想象一下 SomeEntity 的实例类将项目保存为 [0 => {ITEM}, 1 => {ITEM}, 2 => {ITEM}, 3 => {ITEM}] (对象的索引数组)。如果您向 getAction 发送请求并收到 SomeEntity JSON 格式的前端项目中的对象,对象中这些项目的类型将是对象的索引数组(您可以使用数组方法迭代它们),但是如果您使用 PATCH 方法从对象中删除它们中的一个或多个并收到一个 JSON 响应,你会得到一个包含对象的 Object 类型,因为在 PATCH 请求之后一些键已经被删除,并且响应中 SomeEntity 类的对象不再包含一个索引数组,而是会有一个对象的对象.这是因为,当您将数组转换为 json 对象时,您会得到两种不同的结果
  • 对象数组(数组)如果键被索引(例如:0,1,2,3,...)
  • 如果键没有被索引(例如:0,2,3,6,...)

  • 目前我正在通过修改(手动重新创建元素)现有的 removeItem 来解决这个问题。实体类中的方法,如下所示:
    public function removeItem(Item $item)
    {
    $this->items->removeElement($item);

    if (!$this->items->isEmpty()) {
    $items = new ArrayCollection();
    foreach ($this->items as $item) {
    $items->add($item);
    }

    $this->items = $items;
    }

    return $this;
    }

    可能有更好的方法来解决这个问题?你怎么解决这个问题?

    我正在使用 FOSRestBundle 和 JmsSerializerBundle。

    最佳答案

    这似乎是一个常见问题 - 参见 https://github.com/schmittjoh/JMSSerializerBundle/issues/373对于其他有这个问题的人。在删除项目的函数中,肯定有一种更短的方法来解决它,而不是再次循环遍历每个元素:

    public function removeItem(Item $item)
    {
    $this->items->removeElement($item);
    $this->items= new ArrayCollection($this->items->getValues());

    return $this;
    }

    该故障单中列出的其他解决方法可能适合也可能不适合您的需求-如果您想要一个全局解决方案,您可以 override the JsonSerializationVisitor转换为数组的类。

    关于json - 在 REST API 中索引数组集合元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35250599/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com