Kate
Kate

Reputation: 57

AS3, PHP & JSON - Decoding one object is fine, an array returns null

I've been hunting around for a few hours and I still have no idea what's going on. I'm new to PHP, but fairly comfortable with simple Flash stuff.

I'm passing a JSON object from PHP into Flash AS3 using URLLoaders, etc. This is my PHP-created test JSON array:

$objJSON = array('sample' => null);
    $objJSON['sample'] = "TESTING";
    $objJSON['sample2'] = "TESTING2";
    $objJSON = json_encode($objJSON);

I return it to flash with

echo "arrayData=$jsonArray";

When I parse that as a SINGLE object in flash, using

var tempJSON = JSON.decode(event.target.data.arrayData);

I get 'TESTING' as my output (textBox.text = tempJSON.sample; using localhost via WAMP), which is correct. Everything looks good, there's communication, the JSON library is being used right, the object is there and accessible...

BUT! When I treat it as an Array (because that's what it is) by changing the code directly above (and touching NOTHING else) to:

var tempJSON:Array = JSON.decode(event.target.data.arrayData, true);

I throw a compiler error of:

TypeError: Error #1009: Cannot access a property or method of a null object reference. at com.adobe.serialization.json::JSONTokenizer/nextChar()[....\json\JSONTokenizer.as:545]

Running the swf in localhost gets me no return where I used to get string. Am I making some newbie mistake that the data suddenly becomes null when I treat it like an array?

I've checked the validity of my JSON via the output in PHP and it checks out. I've made sure I have no extra echos in the PHP class being called. I'm just stumped.

FIX'D!

Guided by the comments, I basically wasn't forming my JSON to be an array, just objects with multiple properties. The correct way to do it was:

$objArray = array(
   array(
   "sample1" => "Testing!",
   "sample2" => "Testing2!",
),
   array (
   "sample1" => "Testing!",
   "sample2" => "Testing2!",
  )
);


$objArray = json_encode($objArray);

Upvotes: 2

Views: 1390

Answers (1)

Selosindis
Selosindis

Reputation: 544

I believe it is because your JSON is decoding into an object and not an array. This will happen if you are using non-integer values as your array keys (ie. 'sample', 'sample2').

I'm not overly familiar with AS3, but you will likely need to cast it into an Object-like instance instead of an Array.

$objJSON = array('sample' => "TESTING", 'sample2' => "TESTING2");
echo json_encode($objJSON);

// Will output
{ "sample": "TESTING", "sample2": "TESTING2" }

This is not array notation using JSON. It is object notation.

I hope this helps!

Upvotes: 2

Related Questions