Yii2 - 如何强制响应JSON格式化程序使用对象而不是数组?

4

我知道可以设置 Yii::$app->response->format = \yii\web\Response::FORMAT_JSON,但是如何设置JSON编码标志JSON_FORCE_OBJECT,以便所有数组都将被编码为对象?


1
https://www.yiiframework.com/doc/api/2.0/yii-web-jsonresponseformatter - 04FS
1个回答

5

好的,这并不难:

Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON] = [
    'class' => 'yii\web\JsonResponseFormatter',
    'encodeOptions' => JSON_FORCE_OBJECT,
];

甚至可以作为一行代码:
Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON]['encodeOptions'] = JSON_FORCE_OBJECT;

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