RESTful 响应如何在 Yii2 中返回 JSON 而不是 XML? [英] RESTful response how to return JSON instead of XML in Yii2?

查看:33
本文介绍了RESTful 响应如何在 Yii2 中返回 JSON 而不是 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我遵循 Yii2 的指南,控制器看起来相同,模型有点不同,它连接到数据库(模型之前是从高级模板中的默认模型复制的),并且 web 配置是也和指南一样.

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

UserController.php

<?php
namespace app\controllers;

use yii\rest\ActiveController;

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

web.php ($config)

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
]

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

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

推荐答案

您可以像下面这样初始设置它:

You can set it initially on call like below:

\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 过滤器,如下所示:

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

这篇关于RESTful 响应如何在 Yii2 中返回 JSON 而不是 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆