RESTful响应如何在Yii2中返回JSON而不是XML?

Osc*_*yes 6 yii2

问题是来自Yii2中RESTful服务器的响应以XML形式返回,我需要它们采用JSON格式.

我按照Yii2的指南,控制器看起来一样,模型有点不同,它连接到数据库(模型以前是从高级模板中的默认模型复制的),而web配置也是一样的像指南.

只是为了澄清任何疑问,这里是代码:

UserController.php

<?php
namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}
Run Code Online (Sandbox Code Playgroud)

web.php($ config)

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'WgkzlqvStTfGXY-ToFlQIJRDMX4LUQtY',
            'parsers'=>[
                'application/json'=>'yii\web\JsonParser'
            ]
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
    ],
    'params' => $params,
];
Run Code Online (Sandbox Code Playgroud)

我在配置组件中尝试了设置:

response=>[
    'format'=>yii\web\Response::FORMAT_JSON
]
Run Code Online (Sandbox Code Playgroud)

...但它仍然以XML响应.如何使其以JSON响应?

Ali*_*our 6

您最初可以在通话时设置它,如下所示:

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
Run Code Online (Sandbox Code Playgroud)

例如:

public function actionView($id)
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $user = \app\models\User::find($id);
    return $user;
}
Run Code Online (Sandbox Code Playgroud)

您还可以ContentNegotiator在类行为中使用过滤器,如下所示:

/**
 * @inheritdoc
 */
public function behaviors()
{
return [
    [
        'class' => \yii\filters\ContentNegotiator::className(),
        'only' => ['index', 'view']
        'formats' => [
            'application/json' => \yii\web\Response::FORMAT_JSON,
        ],
    ],
];
}
Run Code Online (Sandbox Code Playgroud)

  • 但是有没有办法全局设置它?而不是在每个控制器中添加它? (2认同)