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

时间:2015-11-10 21:31:17

标签: 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';
}

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 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:1)

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

#import <QuickLook/QuickLook.h>

-(void)viewDidLoad
{
   if ([QLPreviewController canPreviewItem:[[NSBundle mainBundle] URLForResource:@"alice" withExtension:@"pdf"]])
    {
        QLPreviewController *previewController = [[QLPreviewController alloc] init];
        previewController.dataSource = self;
        [previewController.view setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/1.2, self.view.frame.size.height)];

        [self addChildViewController:previewController];
        [viewQuickLook addSubview:previewController.view];
        [previewController didMoveToParentViewController:self];
    }
}


-(NSInteger) numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:@"alice" withExtension:@"pdf"];
    return pdfURL;
}

答案 2 :(得分: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',
]