2580 Posts in 695 Topics by 540 members
Data Model Questions
SilverStripe Forums » Data Model Questions » DataObject::toJSON() method
Moderators: martimiz, Howard, Sean, Ryan M., biapar, Willr, Ingo, swaiba
|
Page:
1
|
Go to End | |
| Author | Topic: | 1697 Views |
-
DataObject::toJSON() method

25 April 2009 at 5:39pm
Hi Guys!
First of all, I just wanted to say that I've started using SilverStripe a month a go, and now, for all my incoming projects, I'll use it! Really, it's wonderful! I'm really amazed about your efforts to bring this wonderful product.
I have a question that is more of a feature request. I would like to know if it would be possible to have a toJSON method for DataObjects ? I've implemented it in DataObject class, but maybe it would be smart to include it in future releases. This method allows me the usage of the powerful evalJSON method of Prototype, because many of my Ajax requests responses are JSON strings, which 90% of the time is a representation of a DataObject...
Tell me what you would think about it. Here's my code (added to DataObject.php) : I'm not sure if I follow the coding standards, but it works. Or maybe there's already a way of doing it that I missed?
/**
* Convert this object to a JSON string. It will includes all the has_one objects recursively.
* TODO: Including default values ???
* @return string The data as a JSON string.
*/
public function toJSON() {
$array = $this->toMap();
foreach($this->has_one() as $relationship => $class) {
if (ClassInfo::exists($class)) {
$component = $this->getComponent($relationship);
$array[$relationship] = $component->exists() ? $this->obj($relationship)->toJSON() : null;
}
}
return json_encode($array);
}From this, in javascript, it's really easy, for example, accessing let's say... a Song Object, for example, related to a File Object...
new Ajax.Request ('url/to/a/song/', {onSuccess: function (response) {
var song = response.responseText.evalJSON();
alert ('Song ID'+song.ID+' is named '+song.Name+' and is located at: '+song.Attachment.Filename);
}});
Thanks and keep on the good work! -
Re: DataObject::toJSON() method

26 April 2009 at 9:43pm
Hey Johnny, welcome to SilverStripe
Try this:
$f = new JSONDataFormatter();
return $f->convertDataObject($myDataObject);RestfulServer makes frequent use of this for converting both DataObjects and DataObjectSets into XML, JSON etc.
-
Re: DataObject::toJSON() method

3 June 2010 at 4:24pm
Hey is this really working?
I used ss 2.3.2 and i got this error when using
$f = new JSONDataFormatter();
return $f->convertDataObject($myDataObject);[User Error] Uncaught Exception: Object->__call(): the method 'inheriteddatabasefields' does not exist on 'DataObjectSet'
-
Re: DataObject::toJSON() method

4 June 2010 at 9:01am
Uhm, because you're using a DataObjectSet instead of a DataObject? ;)
| 1697 Views | ||
|
Page:
1
|
Go to Top |



