Disturbed Coder

Ideas of a disturbed programmer

home | about | donate | twitter

December 12 2012

FlashCS6/FlashPlayer11 JSON Compilation Error


Some projects written for older FlashPlayer versions (including Gaia framework) does not compile anymore with FlashCS6/FlashPlayer11 due an error in JSON class. The problem is the native JSON class which is available in FlashPlayer API since version 11. But older projects commonly use Mike Chambers as3corelib, thus a conflict appears because two classes with the same name are available.

The error is something like this:
1061: Call to a possibly undefined method encode through a reference with static type Class.

Let’s create a basic Actionscript3 application to clarify the situation:

import com.adobe.serialization.json.JSON;
import flash.display.Sprite;

public class JSONTest extends Sprite
{
	public function JSONTest()
	{
		// won't compile
		var result:String = JSON.encode({value: "test"});
		trace(result);
	}
}

Compiling for FlashPlayer9 or 10 no error happens. However using FlashCS6 or FlexSDK4.5 (generating the SWF to player version 11) you get the error. The message tells that the method encode wasn’t found in JSON class.
The reason is the new native JSON class. This class is in global scope (what means you don’t need to import it - like Number).

If you change the code above to use native JSON (see the documentation), the SWF file is generated with success:

import flash.display.Sprite;

public class JSONTest extends Sprite
{
	public function JSONTest()
	{
		// will compile - using native JSON
		var result:String = JSON.stringify({value: "test"});
		trace(result);
	}
}

There’s no ambiguity, since native JSON is at top level.

To use Mike Chambers library, use the following code:

import com.adobe.serialization.json.JSON;
import flash.display.Sprite;

public class JSONTest extends Sprite
{
	public function JSONTest()
	{
		// will compile - using Mike Chambers parser
		var result:String = com.adobe.serialization.json.JSON.encode({value: "test"});
		trace(result);
	}
}

If you inform the package name explicitly the compiler doesn’t gets confused anymore (the perfect fix for older projects, such as Gaia framework).