1

我正在将 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 查看器中的结果也显示了差异

好的:http: //img822.imageshack.us/img822/7034/goodj.jpg

和坏的:http: //img534.imageshack.us/img534/3389/badrk.jpg

4

1 回答 1

2

尝试使用json_encode自己对结果进行编码 ,然后发送结果?查看 json_encode 的 flag 选项,JSON_FORCE_OBJECT 可能对你有帮助

于 2012-05-30T09:18:19.243 回答