Yii JSON

Hi folks,

I'm new to Yii, and I'd like to know if there's any solution, to get a JSON result (nested objects instances of stdClass) in a model, so that I can access them like Yii generated models? I don't want to walk through all objects, and generate my own models.

I have to do this, because I need some extra functionality for all objects in JSON result object (i.e. function getTitle()).

Thx

Dan

Yii models currently can be converted to JSON using CJSON. However, it doesn't support the related objects. To do that, you need to override the following two methods:

public function getIterator()


public function offsetExists($offset)

Quote

Yii models currently can be converted to JSON using CJSON. However, it doesn't support the related objects. To do that, you need to override the following two methods:
public function getIterator()





public function offsetExists($offset)</div></div>

I already have a JSON object and would turn it into a model (not model into JSON).

oops, sorry for misunderstanding. There's no direct way in Yii. From what I can see, the main problem here is how to know the class name. If that is not a problem, you can populate the AR attributes and related objects using the following two methods:

addRelatedRecord()

setAttributes()

No problem :slight_smile:

By Now, if done it in this way.

In the model class:

class MyModel

{

  function __construct(&$obj)

  {

    if (is_object($obj)) {

      foreach ($obj as $var => $value ){

        $this->$var = $value;

      }

    }

    return $this;

  }

}

and in the controller class (which gets the json result by cURL):

foreach ($json->result as $intIndex) {

  $json->result[$intIndex] = new MyModel($json->result[$intIndex]);

}

which is turning all instances of stdClass in $json->result into instances of MyModel.

I don't think that's an elegant (or performant) way, but it work's. Until there's no other solution, I'll keep it doing this way.

Something like casting would be great, i.e.:

foreach ($json->result as $intIndex) {

  $json->result[$intIndex] = (MyModel) $json->result[$intIndex];

}

but this doesn't work :frowning: