Magento – json encode in magento 2

jsonmagento2

I just wanted to know that what is the right way to print array data into json format. I Know we can use php function json_encode() but is this the right way to print array data? Because i saw one of magento's core file, there was something like this

        if (!$_isValidFormKey || !$_isValidSecretKey) {
        $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
        $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true);
        if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) {
            $this->getResponse()->representJson(
                $this->_objectManager->get(
                    \Magento\Framework\Json\Helper\Data::class
                )->jsonEncode(
                    ['error' => true, 'message' => $_keyErrorMsg]
                )
            );
        } else {
            $this->_redirect($this->_backendUrl->getStartupPageUrl());
        }
        return false;
    }
    return true;
}

so if we look at this section

$this->getResponse()->representJson(
                $this->_objectManager->get(
                    \Magento\Framework\Json\Helper\Data::class
                )->jsonEncode(
                    ['error' => true, 'message' => $_keyErrorMsg]
                )
            );

we see magento is encoding data using \Magento\Framework\Json\Helper\Data class.

I am working on custom APIs where i need to send data in json format. So please correct me if i am not wrong that we can also print Array data using this \Magento\Framework\Json\Helper\Data class.

Thankyou.

Best Answer

Nowadays, the recommended dependency to inject would be the \Magento\Framework\Serialize\SerializerInterface.