AS3: Creating an array of objects for storing JSON data


/ Published in: ActionScript 3
Save to your folder(s)

Notes to self: re-use this for other projects


Copy this code and paste it in your HTML
  1. private var _myObjArr:Array = new Array(); // array of objects
  2. private var _stringAuthor:String;
  3. private var _stringDate:String;
  4. private var _stringText:String;
  5.  
  6. /**
  7. * Success handler after requesting JSON data from server
  8. *
  9. * @param event Event
  10. * @return void
  11. */
  12. private function onSuccess(event:Event):void
  13. {
  14. var loader:URLLoader = event.target as URLLoader;
  15. var data:Object = null;
  16.  
  17. try { // get the raw JSON data
  18. data = JSON.decode(loader.data);
  19.  
  20. } catch(e:Error) {
  21. trace("Error requesting document");
  22. }
  23.  
  24. loader.close();
  25. loader = null;
  26.  
  27. if (data !=null)
  28. {
  29.  
  30. if (data.error)
  31. {
  32. trace(data.error);
  33.  
  34. } else {
  35. // loop thru data
  36. for (var key:Object in data) {
  37.  
  38. _stringAuthor = '<p><span class="author">' + data[key].author + '</span></p>';
  39.  
  40. _stringDate = '<span class="date">' + data[key].date + '</span></p>';
  41.  
  42. _stringText = '<p><span class="text"> "' + data[key].text + '"</span></p>';
  43.  
  44.  
  45. // save Author, Date, Text to an object array _myObjArr
  46. var obj:Object = new Object();
  47. obj.Author = _stringAuthor;
  48. obj.Date = _stringDate;
  49. obj.Text = _stringText;
  50. _myObjArr.push(obj);
  51.  
  52. }
  53.  
  54. }
  55. }
  56.  
  57. } // end onSuccess
  58.  
  59. // now that we got all our info saved, we can retrieve it later in other functions like:
  60.  
  61. for(var i:uint = 0; i < _myObjArr.length; i++) {
  62. _blogPost[i] = addBlogPosts();
  63. addChild(_blogPost[i]);
  64. }
  65.  
  66. // does this snippet help anyone?

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.