I've created my custom controller and I want to return the result formated with JSON. I always get a JSON parse error "JSON.parse: unexpected character at line 1 column 1 of the JSON data" and the result is always in the following format:
array(0) { } {"Test-Message":""}
I've tried following variations of code, but nothing solved the problem
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;
}