0

what is equivalent in m2.If we want to convert below code in magento2 which class we can use to send json response directly from helper class.

Mage::app()->getResponse()->clearHeaders()
                    ->setHeader('Content-Type','application/json')
                    ->setBody($jsonContent)->sendResponse();                   
                    exit;
1
  • Use "Magento\Framework\Controller\Result\Json" for return.
    – Sohel Rana
    Commented Aug 1, 2022 at 10:06

2 Answers 2

0

Class :- Magento\Framework\Controller\Result\JsonFactory;

$resultJson = $this->resultJsonFactory->create();
$resultJson->setHeader('Content-Type','application/json');
$resultJson->setBody($jsonContent);
$resultJson->sendResponse();   
1
  • getting error Call to undefined method Magento\Framework\Controller\Result\Json\Interceptor::setBody()
    – M2 Dev
    Commented Aug 1, 2022 at 10:15
0

Within a controller try

Using an array

$jsonArray = []

/** \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory **/
$resultJson = $this->resultJsonFactory->create();
$resultJson->setJsonData($jsonArray);
return $resultJson;

Using raw JSON content

/** \Magento\Framework\Controller\Result\RawFactory $resultRawFactory **/
$result = $this->resultRawFactory->create();
$result->setHeader('Content-Type','application/json');
$result->setContents($jsonContent);
return $result;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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