小さな REST WS に CodeIgniter を使用していますが、(Jackson パーサーの観点から見て) 適切にフォーマットされた 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が正しく機能していると思います。
EDITED: のようなクラスを追加した後、まだ運がありません
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 ビューアの結果も違いを示しています。