dongpang2483
2013-10-22 07:39
浏览 163

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

图片转代码服务由CSDN问答提供 功能建议

在magento中我们使用其余的url来访问数据,如 http:// localhost / magento / api / rest / products 它以xml格式返回,而不是我需要JSON。

我尝试了以下代码,但没有用

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

位于文件夹\ 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);
    }
    
    打赏 评论
  • duansha6410 2013-10-22 08:04

    I guess your $jsonData is not actually JSON. Try using a json helper

    $jsonData = Mage::helper('core')->jsonEncode($data)
    
    打赏 评论

相关推荐 更多相似问题