yii2 rest api创建自定义响应正文

时间:2018-02-06 14:25:36

标签: rest yii2

请帮助新手, 如何获得这样的响应,我从ActiveController扩展, actionIndex是返回SearchModel的prepareDataProvider。

 {
   "success": true,
   "result": {
     "list": [
       {
         "id": 1,
         "name": "List title"
         "list":[]
       }
     }
    ]
  }
}

enter code here

我用

public $serializer = [
    'class' => 'yii\rest\Serializer',
    'collectionEnvelope' => 'list',
];

得到

enter code here

{
    "list": [
        {
          "id": 12,
          "name": "api list 6 ",
          "list": "6 create "
        },
        {
          "id": 13,
          "name": "api list 10 crt ",
          "list": "10 crt "
      },
  ]
}

这是针对react.js app

1 个答案:

答案 0 :(得分:0)

yii\rest\Serializer是负责样式化数据输出的类。在您的情况下,您只需要根据您的需要调整those lines in source code。创建一个扩展原始类的新类,并按如下方式调整方法输出:

<?php
namespace app\components;

class Serializer extends \yii\rest\Serializer
{
     /**
     * {@inheritdoc}
     */
    protected function serializeDataProvider($dataProvider)
    {
        $output = parent::serializeDataProvider($dataProvider);

        if (!is_array($output)) return $output;

        return [
            'success' => true,
            'result' =>  $output
        ] ;
    }
}

然后让你的控制器使用它而不是原来的:

public $serializer = [
    'class' => 'app\components\Serializer',
    'collectionEnvelope' => 'list',
];

这应该足以获得以下输出:

{
    "success": true,
    "result": {
        "list": [ {...}, {...}, {...} ],
        "_links": {...},
        "_meta": {...}
    }
}