Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to get jsonEncode in magento2

Magento has its own json encode and decode functions:

Mage::helper('core')->jsonEncode($array);  

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

like image 439
vijay b Avatar asked Aug 31 '16 06:08

vijay b


1 Answers

Magento 2 way is pass Magento\Framework\Json\Helper\Data using DI functionality (see blow). Don't use $this->helper() and objectManager. This functionality will be deprecated soon.

/**
 * @var \Magento\Framework\Json\Helper\Data
 */
protected $jsonHelper;

/**
 * Constructor.
 * 
 * @param \Magento\Framework\Json\Helper\Data $jsonHelper
 */
public function __construct(\Magento\Framework\Json\Helper\Data $jsonHelper)
{
    $this->jsonHelper = $jsonHelper;
}

/**
 * @param array $dataToEncode
 * @return string
 */
public function encodeSomething(array $dataToEncode)
{
    $encodedData = $this->jsonHelper->jsonEncode($dataToEncode);

    return $encodedData;
}
like image 117
Igor Sydorenko Avatar answered Oct 01 '22 16:10

Igor Sydorenko