【问题标题】:Need to return JSON with keys through Magento 2 webapi, but M2 removes first-level keys需要通过 Magento 2 webapi 返回带有键的 JSON,但是 M2 去掉了一级键
【发布时间】:2019-09-13 15:36:25
【问题描述】:

我想通过 webapi 从 M2 返回 JSON

但是 M2 删除了一级键

为什么会这样?它是功能还是错误?可以忽略吗?

Magento 2.3.2

在 webapi.xml 中

    <route url="/V1/testapi" method="GET">
        <service class="Vendor\Module\TestApi" method="fetch"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

类TestApi

<?php
namespace Vendor\Module\Model;

class TestApi
{ 
   /**
     * @return string
     */
    public function fetch() {
        return [
            'level1_key1' => [
                'level2_key1' => 'testvalue',
            ],
            123 => 'test',
            'level1_key2' => 2,
        ];
    }
}

预期结果:

{
    "123": "test",
    "level1_key1": {
        "level2_key1": "testvalue"
    },
    "level1_key2": 2
}

实际结果:

[
    {
        "level2_key1": "testvalue"
    },
    "test",
    2
]

【问题讨论】:

    标签: json rest magento2


    【解决方案1】:

    请参阅this question,我认为那里给出的答案将适用于您的问题。

    【讨论】:

      【解决方案2】:

      如果有人仍在为此寻找解决方案,要使用带有关联键的 json,您必须返回关联数组的数组:

      <?php
      namespace Vendor\Module\Model;
      
      class TestApi
      { 
         /**
           * @return string
           */
          public function fetch() {
              $result = [
                  'level1_key1' => [
                      'level2_key1' => 'testvalue',
                  ],
                  123 => 'test',
                  'level1_key2' => 2,
              ];
              return [$result];
          }
      }
      

      然后你会得到类似的东西:

      [
          {
              "level1_key1": {
                  "level2_key1": "testvalue"
              },
              "123": "test",
              "level1_key2": 2
          }
      ]
      

      【讨论】:

      • umm.. no )因为它改变了数据结构(更深一层)。当然它有用的技巧,但仍然不是正确的解决方案。不幸的是,没有“开箱即用”的解决方案。您必须更改数据结构(例如,如本答案所示)或修改 Magento 核心
      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2011-07-15
      • 2022-01-16
      • 2015-12-24
      相关资源
      最近更新 更多