如何在 Flex 3 中使用原生 JSON 或 actionjson 解码 Json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9667291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode Json using native JSON or actionjson in Flex 3
提问by AabinGunz
I have the below Json (wf.json)
我有以下 Json (wf.json)
{
"workflow":{
"template":"Analysis1",
"start":{
"instance":"HDA_run1",
"user":"symtest",
"date":"3-Mar-2012",
"timestamp":"1330948220475"
},
"host":{
"name":"bartla",
"user":"symtest1",
"password":"symtest1",
"installpath":"",
"product":""
},
"javadump":{
"pid":"8989",
"corefilename":"",
"heapdump":"",
"stack":"",
"JAVA_HOME":""
},
"mat":{
},
"email":{
"to":"[email protected]",
"subject":"",
"message":""
},
"end":{
}
}
}
As you can see there are 7 items (or sub headings inside main heading workflow). Under each item it can have another set of properties eg: email (item)has 3 properties ("name":"value").
如您所见,有 7 个项目(或主标题内的子标题workflow)。在每个项目下,它可以有另一组属性,例如:电子邮件(item)有 3 个属性("name":"value")。
So based on the number of properties I need to be able to create controls (Text)in my Flex 3 UI.
因此,根据我需要能够(Text)在 Flex 3 UI 中创建控件的属性数量。
I read herethat actionjsonis 5-6x faster than the as3corelib, but I am not able to find any example code for it. The actionjson doc says it function the same way as corelib, so I even tried import com.adobe.serialization.json.JSON; JSON.decode(rawData)but it is unable to find JSON.
我读到这里是actionjson是5-6x比快的as3corelib,但我无法找到任何示例代码它。actionjson 文档说它的功能与 corelib 相同,所以我什至尝试过,import com.adobe.serialization.json.JSON; JSON.decode(rawData)但无法找到JSON.
Below is my code
下面是我的代码
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" minWidth="955" minHeight="600"
creationComplete="service.send()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
//Alert.show(rawData); This prints my JSON String
var obj:Object = decodeJson(rawData);
/*error call to possibly undefined method decodeJson*/
Alert.show(obj.toString());
}
]]>
</mx:Script>
<mx:HTTPService id="service" resultFormat="text"
url="/cjb/wf.json"
result="onJSONLoad(event)" />
</mx:Application>
Please help me fetch name, valuesif any from each item. Thanks
name, values如果有的话,请帮我从每件物品中取出。谢谢
Is it not possible to directly fetch json data from an object (not custom made) like it is done in jquery?
是否无法像在jquery 中那样直接从对象(非定制)中获取 json 数据?
Update with Flex Build Path
使用 Flex 构建路径更新


回答by RIAstar
If the fastest parser is what you want, then you'll want use native JSON parsing. Its usage is as simple as this:
如果最快的解析器是您想要的,那么您将需要使用原生 JSON 解析。它的用法很简单:
var result:Object = JSON.parse(event.result);
trace(result.workflow.template); //traces "Analysis1"
The JSONclass is located in the root package, so no need to import anything. You can find information on its usage in the docs.
该JSON类位于根包,所以没有必要进口任何东西。您可以在docs 中找到有关其用法的信息。
However native JSON is only available for Flash Player 11 or higher, which means you'll have to target at least that player version. Since your compiling a Flex 3 application, it will target Flash Player 9 by default. If your requirements don't prohibit you from targeting FP11+, the easiest fix is to compile with the Flex 4.6 (or higher) SDK. The screenshot in your question shows that you're using Flex 3.5, so you'll have to change that in the "build path" settings.
但是,本机 JSON 仅适用于 Flash Player 11 或更高版本,这意味着您必须至少针对该播放器版本。由于您编译的是 Flex 3 应用程序,因此默认情况下它将针对 Flash Player 9。如果您的要求不禁止您以 FP11+ 为目标,最简单的解决方法是使用 Flex 4.6(或更高版本)SDK 进行编译。您问题中的屏幕截图显示您使用的是 Flex 3.5,因此您必须在“构建路径”设置中进行更改。
If you wish to traverse the resulting object dynamically, you can do it with a simple 'for' loop:
如果您希望动态遍历结果对象,可以使用简单的“for”循环来完成:
//workflow is the root node of your structure
var workflow:Object = result.workflow;
//iterate the keys in the 'workflow' object
for (var key:String in workflow) {
trace(key + ': ' + workflow[key]);
}
//template: Analysis1
//start: [Object]
//host: [Object]
//...
If you want to do it recursively, you can check whether a value is an Object or not:
如果你想递归地做,你可以检查一个值是否是一个对象:
if (workflow[key] is Object) {
//parse that node too
}
else {
//just use the value
}
回答by Dinesh
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import com.adobe.serialization.json.JSON;
[Embed(source="assets/test.json",mimeType="application/octet-stream")]
private var json_file:Class;
protected function button1_clickHandler(event:MouseEvent):void
{
trace("Hello from Flex Debugging!");
var bytes:ByteArray = new json_file();
var json:String = bytes.readUTFBytes(bytes.length);
trace(json);
var arr:Object = JSON.decode(json);
for (var keyname:String in arr)
{
trace ( keyname + ": " + arr[ keyname ] );
}
grid.dataProvider = arr;
}
]]>
</mx:Script>
<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Age" dataField="age"/>
</mx:columns>
</mx:DataGrid>
<mx:Button x="538" y="45" label="Get Json" click="button1_clickHandler(event)"/>
</mx:WindowedApplication>
test.json
测试文件
{ "name": "dibneg", "age" : "67", "sex": "female", "imagePath": "kamil.jpg" }
{ "name": "dibneg", "age": "67", "sex": "female", "imagePath": "kamil.jpg" }
回答by AabinGunz
After following solution from RIAstar, this is what I did (both Flex 3.5 compiler & 4.6 compiler code)
在遵循 RIAstar 的解决方案之后,这就是我所做的(Flex 3.5 编译器和 4.6 编译器代码)
Flex 3.5 compiler using as3corelib.swc for JSON
Flex 3.5 编译器将 as3corelib.swc 用于 JSON
import com.adobe.serialization.json.JSON;
private var temp:String ='{"workflow":{ "template":"HeapDumpAnalysis", "start":{ "instance":"HDA_run1", "user":"symtest", "date":"3-Mar-2012", "timestamp":"1330948220475" }, "host":{ "name":"estilo", "user":"symtest1", "password":"symtest1", "installpath":"", "product":"" }, "javadump":{ "pid":"8989", "corefilename":"", "heapdump":"", "stack":"", "INFA_HOME":"" }, "mat":{ }, "email":{ "to":"[email protected]", "subject":"", "message":"" }, "end":{ }}}';
private function test():void
{
var obj = JSON.decode(temp);
var workflow:Object = obj.workflow;
for (var key:String in workflow) {
trace(key + ': ' + workflow[key] + (key is String) + ", " + (workflow[key] is String));
}
}
output
输出
javadump: [object Object]true, false
template: HeapDumpAnalysistrue, true
host: [object Object]true, false
end: [object Object]true, false
mat: [object Object]true, false
email: [object Object]true, false
start: [object Object]true, false
Flex 4.6 compiler using native Json parsing
使用原生 Json 解析的 Flex 4.6 编译器
private var temp:String ='{"workflow":{ "template":"HeapDumpAnalysis", "start":{ "instance":"HDA_run1", "user":"symtest", "date":"3-Mar-2012", "timestamp":"1330948220475" }, "host":{ "name":"estilo", "user":"symtest1", "password":"symtest1", "installpath":"", "product":"" }, "javadump":{ "pid":"8989", "corefilename":"", "heapdump":"", "stack":"", "INFA_HOME":"" }, "mat":{ }, "email":{ "to":"[email protected]", "subject":"", "message":"" }, "end":{ }}}';
private function test():void
{
var result:Object = JSON.parse(temp);
var workflow:Object = result.workflow;
for (var key:String in workflow) {
trace(key + ': ' + workflow[key] + (key is String) + ", " + (workflow[key] is String));
}
}
output
输出
javadump: [object Object]true, false
mat: [object Object]true, false
end: [object Object]true, false
email: [object Object]true, false
host: [object Object]true, false
start: [object Object]true, false
template: HeapDumpAnalysistrue, true
回答by DrogoNevets
import com.adobe.serializers.json.JSONDecoder;
var JSON:JSONDecoder = new JSONDecoder();
var result:Object = JSON.decode(JSON_STRING);
that worked for me then you can either construct new object type(s) or jsut access values either
对我有用然后你可以构造新的对象类型或 jsut 访问值
result.template
or
或者
result['template']
the latter is good for dynamic valus/keys needed rather than known key values
后者适用于所需的动态值/键,而不是已知的键值

