How to return a JSON response from a controller

An example of Magento 2 backend controller with JSON response:

<?php
namespace Dfe\Login\Controller\Adminhtml\DfeLogin;
class Google extends \Magento\Backend\App\AbstractAction {
	/**
	 * @param \Magento\Backend\App\Action\Context $context
	 * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
	 */
	public function __construct(
		\Magento\Backend\App\Action\Context $context
		,\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
	) {
		parent::__construct($context);
		$this->resultJsonFactory = $resultJsonFactory;
	}

	/**
	 * @return \Magento\Framework\Controller\Result\Json
	 */
	public function execute() {
		/** @var \Magento\Framework\Controller\Result\Json $result */
		$result = $this->resultJsonFactory->create();
		return $result->setData(['success' => true]);
	}
}

etc/adminhtml/routes.xml:

<?xml version='1.0'?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd'>
	<router id='admin'>
		<route id='adminhtml' frontName='admin'>
            <module name='Dfe_Login' before='Magento_Backend' />
		</route>
	</router>
</config>

Examples from the core

1

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php#L38-L58

2

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Catalog/Controller/Adminhtml/Category/CategoriesJson.php#L36-L41

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Catalog/Controller/Adminhtml/Category/CategoriesJson.php#L48-L64

3

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L135-L143

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L159-L162

https://github.com/magento/magento2/blob/8fd3e8/app/code/Magento/Customer/Controller/Ajax/Login.php#L191-L193

See also: