JSON扫盲帖 JSON.as类教程(2)


import json.*;
var json:Object = new Object();
json = JSON.decode(serverJSON);



json就是一个对象了,简单吧。
举一个例子:
上面的JSON的一段代码:

复制代码 代码如下:


{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}


存入变量:serverJSON
代码:

复制代码 代码如下:


var serverJSON:String = '{ "programmers": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }],"authors": [{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }],"musicians": [{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }]}'
var s:Object = JSON.decode(serverJSON);
//开始使用
trace(s.programmers[0].firstName);//输出:Brett



不是吧这么简单。其实转变后就成为一个对象了,可以通过点语法来访问这些值了。XML靠边去。
2、本地对象做成JSON
你要是能自己拼出JSON字符串也可以,不过我们是在面向对象的世界啊,那么我们都是对象啊,到时候对象直接就可以来用了。
举一个例子:

复制代码 代码如下:


import json.*;
var myObject:Object = new Object();
myObject.ab = "adfsdf";
myObject.cd = Math.random();
trace(JSON.encode( myObject ));//输出:{"ab":"adfsdf","cd":0.0599129400216043}


这样就可以给服务器了。
总结:就两个方法,JSON.decode(String),JSON.encode(Object),有这么简单的方式实现传输量小,而且简单的数据格式,我们为什么还不用呢?
其实XML自然也有他自己的强势,当一个结构复杂的数据结构出现的时候,这个时候JSON就很难搞定了,XML就是首选了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzywd.html