Not able to get Yii2 object data returned as Json

2019-06-22 09:17发布

问题:

I am new to the Yii2 framework and PHP. When I try to retrieve a model data from the server as json, I am getting an empty result. But, when I use var_dump, I am getting a non-empty result.

Controller class code:

public function actionIndex() {          
    $client = new Client();
    $client->name = "ajith";
    echo json_encode($client);
}

Model class code:

class Client extends \yii\mongodb\ActiveRecord {
    public static function collectionName() {
        return ['gym', 'client'];
    }

    public function attributes() {
        return ['_id', 'name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'];
    }

    public function rules() {
        return [
            [['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
        ];
    }

    public function attributeLabels() {
        return [
            '_id'  => 'ID',
            'name' => 'Name',
            'age'  => 'Age',
            'sex'  => 'Sex',
            'phoneno'  => 'Phoneno',
            'email'    => 'Email',
            'address'  => 'Address',
            'location' => 'Location'
        ];
    }
}

When I use the URL path pathToServer/web/client, I am getting result echoed as {}. Why is it so? I use MongoDB as the database.

回答1:

Import Response class:

use yii\web\Response;

Tell Yii what format do you want as result by setting Yii::$app->response->format before return

public function actionIndex() {    
    Yii::$app->response->format = Response::FORMAT_JSON;        
    $data = ["success" => true, "message" => "Hello World"];
    return $data;
}

Response result:

{
    "success": true,
    "message": "Hello World"
}

You can read about response formats in the yii2-cookbook