RESTful response how to return JSON instead of XML in Yii2?

杀马特。学长 韩版系。学妹 提交于 2020-01-03 09:04:25

问题


The problem is that responses from RESTful server in Yii2 come back as XML, and I need them to be in JSON format.

I was following the guide from Yii2, the controller looks the same, the model is kind of different, it is connected to a database (the model was previously copied from a default model in an advanced template), and web config is also the same like the guide.

Just to clarify any doubts, here is the code:

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

I tried settings in the config component:

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

...but it still responds with XML. What do I do to make it respond with JSON?


回答1:


You can set it initially on call like below:

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

For example:

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

You can also use ContentNegotiator filter in your class behaviors like below:

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



回答2:


Just set the Response's format in your application configuration:

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


来源:https://stackoverflow.com/questions/33639985/restful-response-how-to-return-json-instead-of-xml-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!