Magento 2 JSON Response – How to Intercept Controller’s JSON Response

interceptorjsonmagento-2.0magento2

I'm trying to intercept a controller returning a JSON object of Magento\Framework\Controller\Result\Json class. The problem is that no matter if I use a plugin or a preference to "catch" the controller response right after it's created to do what I want with it, I always end up with this Json object, and its only public method inherited from Magento\Framework\Controller\AbstractResult is the renderResult method (apart from some setters, which won't help me at all).The JSON string is also a protected property, so I can't access it directly.

So, how can I get the JSON string from the response object? Of course, I could just replicate some of the controller's logic that creates it and use that instead, but I'm trying to avoid this method if possible.

I'm using the develop branch. I based my code on the 0be91a5 commit (Merge pull request #14 from magento-vanilla/PR), but I checked the latest commit (currently it's 74f9337 Merge pull request #81 from magento-firedrakes/MAGETWO-44741) and there are no changes in the Json and AbstractResult classes.

Best Answer

Class \Magento\Framework\Controller\Result\Json has two public methods for work with data. You can add plugin on their methods to modify json related data:

class \MyVendor\MyModule\Controller\Result\JsonPlugin {
   public function beforeSetData($subject, $data, $cycleCheck = false, $options = []) 
   {
       return [ 'data' => $data, 'metadata' => 'sdsd'];
   }
   public function beforeSetJsonData($subject, $jsonData)
   {  
        return '{"data": ' . $jsonData . , ', "metadata": []}';
   }