Question

I'm not really sure whats required to make an action return json.
I'm sure there is more then one way to skin this cat, but I'm not sure what is absolutely required.

Is it adequate to just $this->render(array('json' => compact('data')); ?
Do I need to add a route specifying its json?
Do I also need to add the media type application/json?
Do I also need to add the default layout default.json.php?
Do I also need to add the view action.json.php?

Notes: I want any arbitrary url: www.mysite.com/Controller/Action to always return json.
I would prefer to be able to specify the return type in my action ONLY (ie, render type).

Was it helpful?

Solution

So it turns out nothing in the op is required other then this line when you return the data at the bottom of the controller action:

    return $this->render(array('json' => $data = array(), 'status'=> 200));

Somethings which should be noted is that the data returned from a recordset is really ugly. Users should do a $recordset->to('array') first. Not sure why, but to('json') ends up escaping all the quotes, which makes the json string really funky.

OTHER TIPS

Returning JSON is easier than you might think. I recently did it and was surprised

I just show it to you by refering to the game i am developing - https://github.com/BitAlchemists/Elenears-Erben/blob/master/app/controllers/MapsController.php

public function view()
{
    $gameId = $this->request->params['id'];
    if($gameId == null)
    {
        return new Response();
    }

    $xSize = 10;
    $ySize = 10;
    $fields = Maps::first(array('game_id' => $gameId))->fields;
    return compact('xSize', 'ySize', 'fields');
}

There you go: You just prepare your data and return it. The magic is done by the Media class. I don't know if you have to add Media.php to Bootstrap.php, just try it out.

I guess the explanation is, that you dont have to provide a view or anything, because Lithium already knows how to present JSON. It also teaches you something what the controller should actually do, because if you would write a view for the same action, it would basically need the same data.

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top