I am using CodeIgniter for some small REST WS, and can not get a properly (as viewed from Jackson parser point of view) formatted JSON output. For Jackson to do it, the output needs to be something like:
{ "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...",
}
]
}
And using the code in CodeIgniter controller like:
$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
I get the following JSON output:
[
[
{
"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..."
}
]
]
Notice the brackets, and the missing name for an array. How to get things right? I suppose the PHP encode_to_json is doing it's job correctly.
EDITED: Still no luck, after adding class like
class Eecipes
{
public $recipes;
public function __construct()
{
}
}
And creating it like
$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);
The output I get is
{
"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..."
}
}
}
So, still not as needed. No angled brackets [, and the numbers are not needed. And the result in online JSON viewer shows the difference, too
The good: http://img822.imageshack.us/img822/7034/goodj.jpg
and the bad: http://img534.imageshack.us/img534/3389/badrk.jpg
Try encoding your result yourself with json_encode and then send the result ? Look at the flag options of json_encode, JSON_FORCE_OBJECT might help you