How to generate a JSON object directly?
package {
import com.adobe.serialization.json.JSON;
import flash.display.Sprite;
public class test3 extends Sprite {
public function test3() {
var str:String = "{\"nations\": " +
"[{\"country\":\"P.R.China\", \"capital\":\"Beijing\"}, " +
"{\"country\":\"U.S.\", \"capital\":\"Washington D.C.\"}]" +
"}";
var json:Object = new Object();
json = JSON.decode(str);
trace(json.nations[0].country);
}
}
}
Output:
P.R.China
You can serialize an object containing primary type members to a JSON object. Remember PRIMARY.
package {
import com.adobe.serialization.json.JSON;
import flash.display.Sprite;
import flash.utils.ByteArray;
public class test3 extends Sprite {
public function test3() {
var example:Example = new Example();
example._int = 3;
example._number = 4.5;
example._string = "hello";
example._boolean = true;
var json:String = JSON.encode(example);
trace(json);
}
}
}
import flash.utils.ByteArray;
class Example {
public var _int:int;
public var _number:Number;
public var _string:String;
public var _boolean:Boolean;
public function Example() {
}
}
output:
{"_number":4.5,"_boolean":true,"_int":3,"_string":"hello"}
Yes, but…
package {
import com.adobe.serialization.json.JSON;
import flash.display.Sprite;
import flash.utils.ByteArray;
public class test3 extends Sprite {
public function test3() {
var example:Example = new Example();
example._int = 3;
example._number = 4.5;
example._string = "hello";
example._boolean = true;
example._byteArray.writeInt(1234);
var json:String = JSON.encode(example);
trace(json);
var result:Object = new Object();
result = JSON.decode(json);
trace(result._byteArray);
}
}
}
import flash.utils.ByteArray;
class Example {
public var _int:int;
public var _number:Number;
public var _string:String;
public var _boolean:Boolean;
public var _byteArray:ByteArray;
public function Example() {
_byteArray = new ByteArray();
}
}
You will see the output:
{"_byteArray":{"length":4,"position":4,"bytesAvailable":0,"objectEncoding":3,"endian":"bigEndian"},"_number":4.5,"_boolean":true,"_int":3,"_string":"hello"}
[object Object]
Yes, only those member of primary types are serialized into JSON result… So CAUTION! When you wanna use JSON, just keep your eyes on PRIMARY types.
-
转载请注明来自柳大的CSDN博客:Blog.CSDN.net/Poechant
-