Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

DataObject::toJSON() method


5 Posts   2805 Views


25 April 2009 at 5:39pm Community Member, 34 Posts

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!


26 April 2009 at 9:43pm Forum Moderator, 801 Posts

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.


29 April 2009 at 4:35am Community Member, 34 Posts

Thanks a lot!



3 June 2010 at 4:24pm Community Member, 57 Posts

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'


4 June 2010 at 9:01am Forum Moderator, 801 Posts

Uhm, because you're using a DataObjectSet instead of a DataObject? ;)