1

I have the following two routines in Flash Builder:

public function getData():void {

    httpService = new HTTPService();
    httpService.url = "https://mongolab.com/api/1/databases/xxx/collections/system.users/?apiKey=xxx";
    httpService.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
    httpService.addEventListener(ResultEvent.RESULT, resultHandler);
    httpService.send();
}

public function resultHandler(event:ResultEvent):void {

    var rawData:String = String(event.result);
    var arr:Array = JSON.decode(rawData) as Array;
    Debug.log(rawData);
    Debug.log(arr);

    httpService.removeEventListener(ResultEvent.RESULT, resultHandler);
}

rawData is displayed as JSON data but arr is displayed as [object Object] rather than an array.

What am I doing wrong?

1 Answer 1

1

this

var jsonStr:String = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S"},"GlossSee": "markup"}}';

will be parsed and JSON.decode returns an Object and you can access the attributes like this:

var obj:* = JSON.decode(jsonStr);
trace(obj.glossary);

this

var jsonStr:String = '[{"title":"asd"},{"title":"asd"},{"title":"asd"},{"title":"asd"}]';

will be parsed and returns an Array (which if you trace it, will return [object Object]).

so if you don't know what data is returned you could just check if

var result:* = JSON.decode(jsonStr);
if (result.length != undefined) {
  // array
  var arr:Array = result as Array;
}
else {
  // object
  var obj:Object = result as Object;
}

a try/catch around decode would also be good, because you don't know if the jsonStr is well-formed...

cheers

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate. Sorry about the delayed response.
if this is the correct answer for you, pls mark it as that. thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.