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;     

 }    
22

If you want to send JSON response from a controller then you have to inject \Magento\Framework\Controller\Result\JsonFactory class to __construct().

See:

     /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    private $jsonResultFactory;

    public function __construct(
    ...
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
    ....
    ) {
    ....
        $this->jsonResultFactory = $jsonResultFactory;
    }

After execute() of your controller should return \Magento\Framework\Controller\Result\Json object

    $data = ['firstname' => 'Amit', 'lastname' => 'bera'];
    $result = $this->jsonResultFactory->create();
    $result->setData($data);
    return $result;
  • 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 '19 at 10:13
  • Sorry donot understand what you want – Amit Bera Apr 3 '19 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 '19 at 10:12
  • can we use resultJsonFactory in model class? – jafar pinjar May 23 '19 at 10:41

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