alex-ks
(13lex)
1
Is it possible to redefine the \yii\helpers\Json class which is used yii2 Rest api to encode the response?
I need to pass JSON_FORCE_OBJECT parameter to json_encode() function, this way: \yii\helpers\Json::encode($order, JSON_FORCE_OBJECT);
How I can do this?
Follow an example.
- Make changes at config:
'components' => [
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
'class' => '\api\components\ApiResponse',
//'class' => 'yii\web\Response'
],
- Create subclass of Response to insert your custom code:
<?php
namespace api\components;
use yii\rest\ActiveController;
use yii\filters\auth\QueryParamAuth;
use Yii;
use yii\web\Response;
class ApiResponse extends \yii\web\Response
{
public function send()
{
if(!$this->isClientError)
{
$this->data = ['status' => ['http_code' => $this->statusCode ], 'data' => $this->data ];
}
else
{
$this->data = ['status' => ['http_code' => $this->statusCode ], 'data' => $this->data ];
}
parent::send();
}
}
alex-ks
(13lex)
3
Looks like I need to redefine yii\web\JsonResponseFormatter::formatJson() method. But not sure how.