2013-07-24 54 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