2013-07-24 52 views
0

我正在Flex中製作一個小型項目(Flash Builder 4.5),用戶可以在其中搜索書籍。目前我可以獲得書籍(即時通過谷歌書籍API),但我收到它作爲JSON格式。將Json解析爲Flex中的XML

我想用xml代替,所以我可以在數據網格中顯示幾個字段。

到目前爲止,我已經下載了as3corelib並將其鏈接到我的項目。但我無法弄清楚如何解碼JSON。 JSON example

<?xml version="1.0" encoding="utf-8"?> 
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx" 
        creationComplete="application1_creationCompleteHandler(event)" 
        > 
<fx:Script> 
    <![CDATA[ 
     import com.adobe.serialization.json.JSON; 

     import mx.controls.Text; 
     import mx.events.FlexEvent; 
     import mx.rpc.events.ResultEvent; 
     [Bindable] private var api_request:String; 

     import com.adobe.serialization.json.JSONDecoder; 


     protected function application1_creationCompleteHandler(event:FlexEvent):void 
     { 
      // TODO Auto-generated method stub 
      btnSearch.addEventListener(MouseEvent.CLICK, Zoek); 
     } 

     protected function Zoek(event:MouseEvent):void 
     { 
      // TODO Auto-generated method stub 
      var api_url:String='https://www.googleapis.com/books/v1/volumes?q='; 
      var api_tag:String=search.text; 

      api_request= api_url + api_tag 

      GoogleBooks.send(); 


     } 

     protected function GoogleBooks_resultHandler(event:ResultEvent):void 
     { 

      txtResult.text=event.result as String; 
      //JSONDecoder(txtResult.text); 

     } 

    ]]> 
</fx:Script> 
<fx:Declarations> 
    <s:HTTPService id="GoogleBooks" url="{api_request}" resultFormat="text" result="GoogleBooks_resultHandler(event)" /> 


</fx:Declarations> 
<s:Button x="175" y="40" label="Button" id="btnSearch"/> 
<s:TextInput x="26" y="38" id="search"/> 

<s:TextArea id="txtResult" x="32" y="112" width="539" height="312"/> 
</s:WindowedApplication> 

所以我的問題是:如何能夠解碼JSON,所以我可以看到XML在我的textarea的?

回答

0

這取決於你想如何使用數據。你可以簡單地做

var data:Object = JSON.decode(jsonString); 

,或者您可以使用JSONDecoder類做相同的:

var decoder:JSONDecoder = new JSONDecoder(jsonString, jsonStringMatchesStandard); 
var data:Object = decoder.getValue(); 

,或者您可以使用JSONDecoder通過令牌字符串標記解碼:

var decoder:JSONDecoder = new JSONDecoder(jsonString, jsonStringMatchesStandard); 
var token:JSONToken = decoder.nextToken(); 

我會建議在資源評論中提供有關如何使用該庫的良好指導。

https://github.com/mikechambers/as3corelib/tree/master/src/com/adobe/serialization/json