我正在将 CodeIgniter 用于一些小型 REST WS,并且无法获得正确(从杰克逊解析器的角度来看)格式化的 JSON 输出。为了让杰克逊做到这一点,输出需要类似于:
{ "recipes":
[
{
"name":"Recipe 1",
"id":"8aecfd9b2fa26e83012fa298c2a50017",
"recipe":"1 Lorem ipsum...",
},
{
"name":"Recipe 2",
"id":"8aecfd9b2fa26e83012fa298c2a90018",
"recipe":"2 Lorem ipsum...",
},
{
"name": "Recipe 3",
"id":"8aecfd9b2fa26e83012fa298c2ae0019",
"recipe":"3 Lorem ipsum...",
}
]
}
并使用 CodeIgniter 控制器中的代码,例如:
$allEecipes['recipes'] = array(
array('name' => 'Recipe 1', 'id' => '8aecfd9b2fa26e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
array('name' => 'Recipe 2', 'id' => '128aecfd9b226e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
array('name' => 'Recipe 3', 'id' => '34ecfd9b2fa26e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
);
$this->response($allEecipes, 200); // 200 being the HTTP response code
我得到以下 JSON 输出:
[
[
{
"name": "Recipe 1",
"id": "8aecfd9b2fa26e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
},
{
"name": "Recipe 2",
"id": "128aecfd9b226e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
},
{
"name": "Recipe 3",
"id": "34ecfd9b2fa26e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
}
]
]
请注意括号和缺少的数组名称。如何把事情做好?我想 PHP encode_to_json 正在正确地完成它的工作。
编辑: 在添加类之后仍然没有运气
class Eecipes
{
public $recipes;
public function __construct()
{
}
}
并像创建它一样
$allEecipes = new Eecipes();
$allEecipes-> recipes = array(
array('name' => 'Recipe 1', 'id' => '8aecfd9b2fa26e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
array('name' => 'Recipe 2', 'id' => '128aecfd9b226e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
array('name' => 'Recipe 3', 'id' => '34ecfd9b2fa26e83012fa298c2a50017', 'recipe' => '1 Lorem ipsum...'),
);
$this->response($allEecipes, 200);
我得到的输出是
{
"recipes": {
"0": {
"name": "Recipe 1",
"id": "8aecfd9b2fa26e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
},
"1": {
"name": "Recipe 2",
"id": "128aecfd9b226e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
},
"2": {
"name": "Recipe 3",
"id": "34ecfd9b2fa26e83012fa298c2a50017",
"recipe": "1 Lorem ipsum..."
}
}
}
所以,仍然没有必要。没有尖括号[,也不需要数字。在线 JSON 查看器中的结果也显示了差异