Search code examples
javascriptjsontitaniumappceleratorappcelerator-mobile

From JSON object to Tableview


I've been messing around with this for a while now, but I can't seem to get it done.

I get tasks as JSON-data back from my API. The data looks like this, printed with Ti.API.info(this.responseText):

[INFO] [{"created_at":"2012-01-09T15:05:25Z","description":"Smullen van onze pizza","id":1,"title":"Pizza Eten","updated_at":"2012-01-09T15:05:25Z","user_id":11},{"created_at":"2012-01-09T15:05:25Z","description":"Lekker Lekker!","id":21,"title":"Ice-Tea Drinken","updated_at":"2012-01-09T15:05:25Z","user_id":11}]

I'm not quite sure how to process this data. I tried a couple of things:

getData.onload = function(){
    var tasks = this.responseText;
    for(t in tasks) {
        Ti.API.info(t);
    }
        }

This printed:

[INFO] 0
[INFO] 1
[INFO] 2
[INFO] 3
[INFO] 4
[INFO] 5
[INFO] 6

till 306.

Another thing I tried was:

var tasks = this.responseText;
for(t in tasks)
{
    if(tasks.hasOwnProperty(t))
    {
        Ti.API.info(t + " -> " + tasks[t]);
    }
}

This gave me:

[INFO] 0 -> [
[INFO] 1 -> {
[INFO] 2 -> "
[INFO] 3 -> c
[INFO] 4 -> r
[INFO] 5 -> e
[INFO] 6 -> a
[INFO] 7 -> t
[INFO] 8 -> e
[INFO] 9 -> d

Another try:

var tasks = this.responseText;
for(t in tasks)
{
    Ti.API.info(t.title);
}

Gave:

[INFO] <null>
[INFO] <null>
[INFO] <null>

I'm really confused how to process this JSON and how to 'prepare' it so i can use it in a tableview. Anyone can help me out here? Thanks.


Solution

  • as skypanther already pointed out. you need to parse your json string to an object. it's well explained at json.org. after you parsed your string into an object it is easy to access its members and create your tableview row.

    /* create the tableview row */
    makeTableViewRow = function(_object){
    
      var row = Ti.UI.createTableViewRow({
         ...
      }]
    
      var title = Ti.UI.createLabel({
         ...
         text: _object.title,
         ...
      });
      row.add(title);
    
      return row;
    };
    
    
    getData.onload = function(){
      var tasks = json.parse(this.responseText), /* parse the json string */
          _rowsForTableView = []; /* put the rows in here */
    
      /* create the rows */
      for (i in tasks){
         var _row = makeTableView(tasks[i]);
         _rowsForTableView.push(_row);
      };
    
      myTableView.setData(_rowsForTableView);
    
    };