5

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;     

 }    

closed as off-topic by Fabian Schmengler, Raphael at Digital Pianism, Qaisar Satti, Amit Bera, benmarks Jun 5 '16 at 19:10

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced OR seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Fabian Schmengler, Raphael at Digital Pianism, Qaisar Satti, Amit Bera, benmarks
If this question can be reworded to fit the rules in the help center, please edit the question.

19

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(
        ...
    );
}
  • 3
    I see no difference of your suggestion. Only that I call the functions in one line... – ClassMP Feb 2 '16 at 12:34
  • 1
    This returns $this rather than $result – LM_Fielding Nov 17 '16 at 15:02
  • 1
    You can also use the resultFactory without a manual dependency injection: $result = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON); – Matthias Kleine May 2 '17 at 11:51
  • @AmitBera,its not working for me,in ROOT\app\etc\env.php path 'MAGE_MODE' => 'developer' changed also but its returning empty array in postman response – Hitesh Balpande Apr 3 at 10:13
  • Sorry donot understand what you want – Amit Bera Apr 3 at 10:14
2
$result = $this->resultJsonFactory->create();

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

After cleaning the Cache and rechecking, this code works now. I don't know what the issue before...

2

You should do...

$result = $this->resultJsonFactory->create();

$result = $result->setData(['Test-Message' => $message]);

return $result; 

I'd suggest to develop in developer mode, to not go through those cache annoying problems. It's very easy to do, go to ROOT\app\etc\env.php and find 'MAGE_MODE' => 'default' ... Change it to 'MAGE_MODE' => 'developer' ... Once you finish change it to 'MAGE_MODE' => 'production' to go live... This is a very awesome feauture in Magento 2. Makes your install really secure once you go live.

  • @AmitBera,its not working for me,in ROOT\app\etc\env.php path 'MAGE_MODE' => 'developer' also but its returning empty array in postman response – Hitesh Balpande Apr 3 at 10:12
  • can we use resultJsonFactory in model class? – jafar pinjar May 23 at 10:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.