public function testSerialize() { $record = $this->users('mike'); $options = array('include' => array('Comments' => array('only' => 'body')), 'only' => 'name'); $serializer = new Mad_Model_Serializer_Json($record, $options); $expected = '{"name":"Mike Naberezny",' . '"Comments":[{"body":"Comment A"},{"body":"Comment B"}]}'; try { $this->assertEquals($expected, $serializer->serialize()); } catch (Mad_Model_Exception $e) { if (function_exists('json_encode')) { throw $e; } else { $this->assertRegExp('/json_encode/', $e->getMessage()); } } }
/** * Returns a JSON string representing the model. Some configuration is * available through <code>$options</code>. * * Without any <code>$options</code>, the returned JSON string will include all * the model's attributes. For example: * * $konata = User::find(1); * $konata->toJson(); * # => {"id": 1, "name": "Konata Izumi", "age": 16, * "created_at": "2006/08/01", "awesome": true} * * The <code>only</code> and <code>except</code> options can be used to limit * the attributes included, and work similar to the <code>attributes</code> * method. For example: * * $konata->toJson(array('only' => array('id', 'name'))); * # => {"id": 1, "name": "Konata Izumi"} * * $konata->toJson(array('except' => array('id', 'created_at', 'age'))); * # => {"name": "Konata Izumi", "awesome": true} * * To include any methods on the model, use <code>:methods</code>. * * $konata->toJson(array('methods' => 'permalink')); * # => {"id": 1, "name": "Konata Izumi", "age": 16, * "created_at": "2006/08/01", "awesome": true, * "permalink": "1-konata-izumi"} * * To include associations, use <code>:include</code>. * * $konata->toJson(array('include' => 'Posts')); * # => {"id": 1, "name": "Konata Izumi", "age": 16, * "created_at": "2006/08/01", "awesome": true, * "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"}, * {"id": 2, author_id: 1, "title": "So I was thinking"}]} * * 2nd level and higher order associations work as well: * * $konata->toJson(array('include' => array('Posts' => array( * 'include' => array('Comments' => array( * 'only' => 'body')), * 'only' => 'title')))); * # => {"id": 1, "name": "Konata Izumi", "age": 16, * "created_at": "2006/08/01", "awesome": true, * "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}], * "title": "Welcome to the weblog"}, * {"comments": [{"body": "Don't think too hard"}], * "title": "So I was thinking"}]} * * @param array $options * @return string */ public function toJson($options = array()) { $serializer = new Mad_Model_Serializer_Json($this, $options); $serialized = $serializer->serialize(); if (self::$includeRootInJson) { $jsonName = $this->getJsonClassName(); return "{ {$jsonName}: {$serialized} }"; } else { return $serialized; } }