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

Yii2 - how to force response JSON formatter to use objects instead of arrays?

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

好吧,没那么难:

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;