json,之前只是了解了下,没太在意。今天,面试被人问到json。就再温习一遍。为什么要用,有哪些好处。这里就不说了。
json由{},[],””,:加字符串组成。基本格式是{“字符串”:”字符串”},也可以像数组一样嵌套。
用到json主要有他的两个方法:decode 和 encode。decode是从服务器取得json,encode是从本地(也就是flash自身)发送给服务器。前者可以理解为解码,后者可以理解为编码。
贴出 AS:
package { import flash.display.Sprite; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.system.System; import flash.events.MouseEvent; import json.JSON; public class Main extends Sprite { private var sdSp:Sprite; private var jsUrl:String = "http://localhost:8080/study/json/json.php"; private var bugua:Boolean = true; private var jsArr:Array = []; public function Main():void { stage.scaleMode = StageScaleMode.NO_BORDER; stage.align = StageAlign.TOP_LEFT; System.useCodePage = true; sdSp=new Sprite(); sdSp.graphics.beginFill(0x0000ff,0.3); sdSp.graphics.drawRect(0,0,100,36); sdSp.graphics.endFill(); sdSp.x = stage.stageWidth / 2 - sdSp.width / 2; sdSp.y = stage.stageHeight / 2 - sdSp.height / 2; addChild(sdSp); sdSp.buttonMode = true; sdSp.addEventListener(MouseEvent.CLICK,clickHandler); } private function clickHandler(e:MouseEvent) { if (bugua) { loadJson(jsUrl); } else { trace("你给我的全部"); jsArr = []; jsArr = [{"date":"2012-11-17","sound":[{"name":"预谋","url":"01.mp3","path":"/mp3/"},{"name":"你Hold住了吗","url":"02.mp3","path":"/mp3/"}]}]; sendJson(jsArr); } bugua = ! bugua; } private function loadJson(url:String) { var myLoader:URLLoader=new URLLoader(); var myRequest:URLRequest=new URLRequest(); myRequest.url = url; myLoader.addEventListener(Event.COMPLETE,getCompleteHandler); myLoader.load(myRequest); } private function getCompleteHandler(e:Event) { var jsonObj:Object = {}; jsonObj = JSON.decode(URLLoader(e.target).data); for (var i in jsonObj) { trace(i+"_"+json[i]); for (var j in jsonObj[i]) { trace(i+"_"+j+"_"+jsonObj[i][j]); } } } private function sendJson(array:Array):void { var jsonString:String = JSON.encode(jsArr); var myLoader:URLLoader=new URLLoader(); var myVariables:URLVariables=new URLVariables(); myVariables.json = jsonString; var myRequest:URLRequest=new URLRequest(); myRequest.data = myVariables; myRequest.method = URLRequestMethod.POST; myRequest.url = jsUrl; myLoader.addEventListener(Event.COMPLETE,sendCompleteHandler); myLoader.load(myRequest); } private function sendCompleteHandler(e:Event) { trace(e.target.data); } } }