Magento2自定义API接口返回JSON格式数据

3.81K 浏览开发笔记

Magento2自定义API接口返回JSON格式数据

之前在写Magento2 Rest Api,使用php的原生方法 json_encode()返回Json数据,但是前端接收到的是字符串,并不是标准的Json格式,虽然可以在前端将数据转码成Json,但是使用起来很不方便,Magento官方文档并没有说明如何返回标准的Json格式,网上相关资料非常少,有一种在Api目录下面添加Data的办法,感觉略显麻烦,最后根据Magento的核心文件找到了一个很方便的解决方案。

在Model目录(或者Api目录)下新建文件ServiceOutputProcessor.php

<?php /**  * Copyright © 2015 Magento. All rights reserved.  * See COPYING.txt for license details.  */ namespace AllduHelloModel; /**  * Data object converter for REST  */ class ServiceOutputProcessor extends MagentoFrameworkWebapiServiceOutputProcessor {     public function process($data, $serviceClassName, $serviceMethodName)     {         /** @var string $dataType */         $dataType = $this->methodsMapProcessor->getMethodReturnType($serviceClassName, $serviceMethodName);         if ($dataType == &#39;array&#39;) {             return $data;         } else {             return $this->convertValue($data, $dataType);         }     } }

etc/di.xml添加

<preference for="MagentoFrameworkWebapiServiceOutputProcessor" type="AllduHelloModelServiceOutputProcessor" />

Api接口文件注释return改为array

@return array

上传到服务器di一下

0