JSON是经常会用到的数据格式,在各个语言中都会使用到。起到和xml同样的作用,但是解析效率要比xml要高。下边是在AS3里边的一个小例子:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import com.adobe.serialization.json.JSON;
private function init():void{
parseJsonToObj();
parseObjToJson();
}
private function parseJsonToObj():void{
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 obj:Object = JSON.decode(serverJSON);
Alert.show(obj.programmers[0].firstName); //output:Brett
Alert.show(obj.authors[1].genre); //output:fantasy
}
private function parseObjToJson():void{
var obj:Object = new Object();
obj.id = "20080728" ;
obj.name = "Tony";
var obj1:Object = new Object();
obj1.firstName = "xie";
obj1.lastName = "yanfeng";
obj.value = obj1;
var str:String = JSON.encode(obj);
Alert.show(str);
//output: {"name":"Tony","value":{"lastName":"yanfeng","firstName":"xie"},"id":"20080728"}
}
]]>
</mx:Script>
</mx:Application>
另外,该程序中需要用到corelib.swc包中的JSON类。corelib.swc是adobe官方的类库,除了json外,还有其他一些比较常用的工具类,比如ArrayUtil、XmlUtil等等。