无法在Yii2 API中返回JSON响应

问题描述

我正在尝试返回JSON响应。

$rec = Yii::$app->hescoMDC->createCommand(/** @lang text */ "SELECT * FROM a_data_catalogue d WHERE d.`METER_ASSET_NO` = '$new_msn' AND d.`disCARD_TIME` IS NULL")->queryOne();
             
 if($rec['CONS_NO'])
                {

                    
                    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                    return Json::encode([
                        'status' => 'Not OK','description' => 'New msn is already attached with a customer ' . $rec['CONS_NO'].' MCO can`t be done'
                    ]);
                       
                }

我正在使用postman来检查响应,但是我看到一个窗口。

解决方法

首先,当您使用时:

  Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

您不需要使用Json::encode()作为回报。只需返回数组