|
|
|
@ -10,7 +10,8 @@
|
|
|
|
|
通过 [[yii\rest\Serializer]] 来完成。 |
|
|
|
|
3. 通过内容协商步骤将数组转换成字符串。 |
|
|
|
|
[[yii\web\ResponseFormatterInterface|response formatters]] 通过 |
|
|
|
|
[[yii\web\Response::formatters|response]] 应用程序组件来注册完成。 |
|
|
|
|
[[yii\web\Response::formatters|response]] 应用程序 |
|
|
|
|
组件来注册完成。 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## 内容协商 <span id="content-negotiation"></span> |
|
|
|
@ -154,3 +155,33 @@ Content-Type: application/json; charset=UTF-8
|
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
### Controlling JSON output |
|
|
|
|
|
|
|
|
|
The JSON response is generated by the [[yii\web\JsonResponseFormatter|JsonResponseFormatter]] class which will |
|
|
|
|
use the [[yii\helpers\Json|JSON helper]] internally. This formatter can be configured with different options like |
|
|
|
|
for example the [[yii\web\JsonResponseFormatter::$prettyPrint|$prettyPrint]] option, which is useful on development for |
|
|
|
|
better readable responses, or [[yii\web\JsonResponseFormatter::$encodeOptions|$encodeOptions]] to control the output |
|
|
|
|
of the JSON encoding. |
|
|
|
|
|
|
|
|
|
The formatter can be configured in the [[yii\web\Response::formatters|formatters]] property of the `response` application |
|
|
|
|
component in the application [configuration](concept-configuration.md) like the following: |
|
|
|
|
|
|
|
|
|
```php |
|
|
|
|
'response' => [ |
|
|
|
|
// ... |
|
|
|
|
'formatters' => [ |
|
|
|
|
\yii\web\Response::FORMAT_JSON => [ |
|
|
|
|
'class' => 'yii\web\JsonResponseFormatter', |
|
|
|
|
'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode |
|
|
|
|
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, |
|
|
|
|
// ... |
|
|
|
|
], |
|
|
|
|
], |
|
|
|
|
], |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
When returning data from a database using the [DAO](db-dao.md) database layer all data will be represented |
|
|
|
|
as strings, which is not always the expected result especially numeric values should be represented as |
|
|
|
|
numbers in JSON. When using the ActiveRecord layer for retrieving data from the database, the values for numeric |
|
|
|
|
columns will be converted to integers when data is fetched from the database in [[yii\db\ActiveRecord::populateRecord()]]. |
|
|
|
|