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

11

问题是Yii2中RESTful服务器的响应以XML形式返回,而我需要它们以JSON格式返回。

我遵循了Yii2指南,控制器看起来一样,在连接到数据库的模型方面有所不同(该模型先前是从高级模板中的默认模型复制的),web config也与指南相同。

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

UserController.php

<?php
namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}

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,
];

我尝试在配置组件中进行设置:

response=>[
    'format'=>yii\web\Response::FORMAT_JSON
]

...但它仍然响应XML。我该怎么做才能让它响应JSON?

3个回答

11

你可以在调用时进行初始设置,例如:

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

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

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

2
但是有没有一种方法可以全局设置它?而不是在每个控制器中添加它? - Oscar Reyes
@nosthertus 看一下 https://dev59.com/2l4d5IYBdhLWcg3wFPQ7 - Ali MasudianPour
我尝试了你通过控制器的方法,它可以工作,但是我尝试了你参考帖子中展示的方法,它不起作用,仍然会响应为XML,你可以在这里看到代码:http://pastebin.com/PawqVx7X - Oscar Reyes

1

只需在应用程序配置中设置响应的格式:

'components' => [
    ... // config
    'response' => [
        'format' => \yii\web\Response::FORMAT_JSON
    ],
    ... // config
]

0
另一种方法是派生自定义响应类并根据数据类型设置格式。
class Response extends \yii\web\Response
{
    protected function prepare()
    {
        if (is_object($this->data) || is_array($this->data)) {
            $this->format = self::FORMAT_JSON;
        }
        return parent::prepare();
    }
}

然后在配置文件中注册此类型。

'response' => [
    'class' => 'app\components\Response',
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接