Q:

Zend2 - How to get the data in Zend\View\Model\JsonModel Object?

How can I get the data in Zend\View\Model\JsonModel Object?
Following this article, I have this code below,
public function create($data)
{
    $form = new AlbumForm();
    $album = new Album();
    $form->setInputFilter($album->getInputFilter());
    $form->setData($data);
    if ($form->isValid()) {
        $album->exchangeArray($form->getData());
        $id = $this->getAlbumTable()->saveAlbum($album);
    }

    print_r($this->get($id));

    return new JsonModel(array(
        'data' => $this->get($id),
    ));
}

With this print_r($this->get($id));, I get, 
Zend\View\Model\JsonModel Object
(
    [captureTo:protected] => 
    [jsonpCallback:protected] => 
    [terminate:protected] => 1
    [children:protected] => Array
        (
        )

    [options:protected] => Array
        (
        )

    [template:protected] => 
    [variables:protected] => Array
        (
            [data] => Album\Model\Album Object
                (
                    [id] => 15
                    [artist] => The  Military  Wives
                    [title] => In  My  Dreams
                    [inputFilter:protected] => 
                )

        )

    [append:protected] => 
)

But how can I get this below as my result?
           [data] => Album\Model\Album Object
                (
                    [id] => 15
                    [artist] => The  Military  Wives
                    [title] => In  My  Dreams
                    [inputFilter:protected] => 
                )

A:

Since JsonModel serializes all passed variables to the nested arrays & strings to represent that variable as JSON, passing an Object instance to JsonModel will be meaningless in this scenario.
Try to pass array representation of your Album object to JsonModel:
return new JsonModel(array("data" => $album->extract()));

or
return new JsonModel(array("data" => $album->toArray()));

And don't forget adding toArray() or èxtract() method to your Album model:
class Album
{
    public function extract()
    {
       return [
           'id' => $this->id,
           'artist' => $this->artist,
           // ...
       ];
    }
}

You may also want implementing JsonSerializable interface.

