dongpang2483 2013-10-22 07:39
浏览 189
已采纳

REST API以JSON格式的响应

In magento as we use the rest url to access the data, as http://localhost/magento/api/rest/products it returns in xml format instead of that I need JSON.

I have tried below code, but no use

$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($jsonData);

in the folder \magento\app\code\core\Mage\Api\Controller\Action.php

  • 写回答

2条回答 默认 最新

  • dsubq24666 2013-10-22 08:03
    关注

    vinox, you should override the default file Request.php. copy \app\code\core\Mage\Api2\Model\Request.php to your local directory and add the following code just before end of the getAcceptTypes() Method.

    unset($orderedTypes);
    $orderedTypes=Array("application/json" => 1);
    

    in other way your getAcceptTypes() method should look like this.

    public function getAcceptTypes(){
    $qualityToTypes = array();
    $orderedTypes   = array();
    
    foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
        $typeWithQ = explode(';', $definition);
        $mimeType  = trim(array_shift($typeWithQ));
    
        // check MIME type validity
        if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
            continue;
        }
        $quality = '1.0'; // default value for quality
    
        if ($typeWithQ) {
            $qAndValue = explode('=', $typeWithQ[0]);
    
            if (2 == count($qAndValue)) {
                $quality = $qAndValue[1];
            }
        }
        $qualityToTypes[$quality][$mimeType] = true;
    }
    krsort($qualityToTypes);
    
    foreach ($qualityToTypes as $typeList) {
        $orderedTypes += $typeList;
    }
    unset($orderedTypes);
    $orderedTypes=Array("application/json" => 1);
    return array_keys($orderedTypes);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL