首页>Magento>source

我已经创建了自定义控制器,我希望返回使用JSON格式化的结果.我总是得到一个JSON解析错误"JSON.parse:JSON数据第1行第1列的意外字符",结果总是采用以下格式:

array(0) { } {"Test-Message":""}

我尝试过以下代码变体,但没有解决问题

public function execute()
{
    $message = "";
    $userName = $this->_request->getParam('user_name');
    try
    {
        //Check user name
        $result = $helper->checkUserName($userName);
        if ($result)
        {
            $message = "Test";
        }
    }
    catch(\Exception $e)
    {
        $message = $e;
    } 
    //$this->getResponse()->setBody($message);
/*
    $arr = array('result' => $message);
    $jsonData = json_encode(array($arr));
    $this->getResponse()->setHeader('Content-type', 'application/json');
    $this->getResponse()->setBody($jsonData);               
*/
/*      
   $this->getResponse()->clearHeaders()->setHeader('Content-type', 'application/json', true);
   $this->getResponse()->clearBody();
    echo $this->getResponse()->getBody();
*/
/*
    $arr = array('result' => $message);
    $jsonData = json_encode(array($arr));
    $this->getResponse()->clearHeaders();
    $this->getResponse()->representJson($jsonData);
*/
/*
    $result = $this->resultJsonFactory->create();
    return $result->setData(['message' => $message]);       
*/
   /** @var \Magento\Framework\Controller\Result\Json $result */
    $result = $this->resultJsonFactory->create();
    /** You may introduce your own constants for this custom REST API */
    $result->setData(['Test-Message' => $message]);
    return $result;     
 }   
最新回答
  • 2019-12-5
    1 #

    Just try with

    return $this->resultJsonFactory->create()->setData(['Test-Message' => $message])

    instead of:

    $result = $this->resultJsonFactory->create();
    $result->setData(['Test-Message' => $message]);
    return $result; 
    

    Note: on __construct function, You need to add jsonFactory class

    protected $resultJsonFactory;
    public function __construct(
        ...
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
        ...
    ) {
        ...
        $this->resultJsonFactory = $resultJsonFactory;
        ...
        parent::__construct(
            ...
        );
    }
    

  • 2019-12-5
    2 #

    $result = $this->resultJsonFactory->create();
        $result->setData(['Test-Message' => $message]);
        return $result;
    

    清理缓存并重新检查后,此代码现在可以正常工作.我不知道之前的问题...

  • 2019-12-5
    3 #

    你应该做......

    $result = $this->resultJsonFactory->create();
    $result = $result->setData(['Test-Message' => $message]);
    return $result;
    

    我建议在开发者模式下开发,不要经历那些缓存烦人的问题.这很容易,去ROOT \ app \ etc \ env.php并找到 'MAGE_MODE' => 'default' ... Change it to 'MAGE_MODE' => 'developer' ... Once you finish change it to 'MAGE_MODE' => 'production'   上线...这是Magento 2中非常棒的特色。一旦你上线,你的安装真的很安全.

  • magento2:使用REST API上载图像时,MIME类型无效
  • 测试magento核心功能