Flash 如何在actionscript 3.0(as3)中创建字符串形式的对象
如何从字符串创建动态对象 以下是我的当前代码,结果不正确:Flash 如何在actionscript 3.0(as3)中创建字符串形式的对象,flash,actionscript-3,actionscript,Flash,Actionscript 3,Actionscript,如何从字符串创建动态对象 以下是我的当前代码,结果不正确: var s1:String = '{x:200, y:400}'; var o1:Object = Object(s1); trace(o1); // result = {x:200, y:400} trace(o1.x) // result = ReferenceError: Error #1069: Property x not found on String and there is no default value. trac
var s1:String = '{x:200, y:400}';
var o1:Object = Object(s1);
trace(o1); // result = {x:200, y:400}
trace(o1.x) // result = ReferenceError: Error #1069: Property x not found on String and there is no default value.
trace(o1.y) // result = ReferenceError: Error #1069: Property x not found on String and there is no default value.
我希望前面的代码输出以下内容:
trace(o1); // result = [object Object]
trace(o1.x); // result = 200
trace(o1.y); // result = 400
提前谢谢 包含一个JSON解析器,可以为您执行此操作。请确保您研究了,因为此库没有新版本,而且其中存在大量的bug,这些bug主要在问题列表中解决。我不知道这是否是最好的方法,但是:
var serializedObject:String = '{x:200,y:400}'
var object:Object = new Object()
var contentWithoutBraces:String = serializedObject.substr(serializedObject.indexOf('{') + 1)
contentWithoutBraces = contentWithoutBraces.substr(0, contentWithoutBraces.lastIndexOf('}'))
var propertiesArray:Array = contentWithoutBraces.split(',')
for (var i:uint = 0; i < propertiesArray.length; i++)
{
var objectProperty:Array = propertiesArray[i].split(':')
var propertyName:String = trim(objectProperty[0])
var propertyValue:String = trim(objectProperty[1])
object[propertyName] = Object(propertyValue)
}
trace(object)
trace(object.x)
trace(object.y)
var serializedObject:String='{x:200,y:400}'
变量对象:对象=新对象()
var contentWithoutBraces:String=serializedObject.substr(serializedObject.indexOf('{')+1)
contentWithoutBraces=contentWithoutBraces.substr(0,contentWithoutBraces.lastIndexOf('}'))
var propertiesArray:Array=contentWithoutBraces.split(','))
对于(变量i:uint=0;i
这会满足你的要求
您可以以递归方式执行此操作,因此,如果对象包含其他对象,也会转换;)
PS:我没有添加trim函数,但是这个函数接收一个字符串并返回一个新字符串,在字符串的开头或结尾没有空格。对于记录,JSON解析器在示例中不会解析字符串,因为JSON需要在成员名周围加引号。因此,字符串:
var s1:String = '{x:200, y:400}';
。。。而必须是:
var s1:String = '{"x":200, "y":400}';
在ActionScript和JavaScript中都有效的对象表示法(如{x:200,y:400})不是有效的JSON,这可能有点令人困惑,但如果我没记错的话,成员名称周围的引号是必要的,以避免可能与保留字发生冲突
较新版本的Flash Player在顶层包含JSON类,请阅读以下文档:
我正要回答同样的问题:)为了解决这个特定的问题,您将在库中使用JSON类:
JSON.decode(str)
和JSON.encode(obj)
来解决这个问题。关于bug,有人在修复它。请参阅:。你只需要从SVN退房。