이 작업을 수행하려면 Person 클래스가 바인딩 가능해야한다고 가정합니다.
그러나 JSON 개체를 사용한다고 말하고 있기 때문에 JSON 문자열에서 구문 분석 한 익명 개체가 있다고 가정합니다. 이 경우에는 작동하지 않을 것이라고 확신합니다. 바인딩 할 수있는 속성이있는 강력한 형식의 개체를 만들어야합니다. 그냥 참고로
:
public static function toInstance(object:Object, clazz:Class):* {
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
// Find the objects and byetArray.writeObject them, adding in the
// class configuration variable name -- essentially, we're constructing
// and AMF packet here that contains the class information so that
// we can simplly byteArray.readObject the sucker for the translation
// Write out the bytes of the original object
var objBytes:ByteArray = new ByteArray();
objBytes.objectEncoding = ObjectEncoding.AMF0;
objBytes.writeObject(object);
// Register all of the classes so they can be decoded via AMF
var typeInfo:XML = describeType(clazz);
var fullyQualifiedName:String = [email protected]().replace(/::/, ".");
registerClassAlias(fullyQualifiedName, clazz);
// Write the new object information starting with the class information
var len:int = fullyQualifiedName.length;
bytes.writeByte(0x10); // 0x10 is AMF0 for "typed object (class instance)"
bytes.writeUTF(fullyQualifiedName);
// After the class name is set up, write the rest of the object
bytes.writeBytes(objBytes, 1);
// Read in the object with the class property added and return that
bytes.position = 0;
// This generates some ReferenceErrors of the object being passed in
// has properties that aren't in the class instance, and generates TypeErrors
// when property values cannot be converted to correct values (such as false
// being the value, when it needs to be a Date instead). However, these
// errors are not thrown at runtime (and only appear in trace ouput when
// debugging), so a try/catch block isn't necessary. I'm not sure if this
// classifies as a bug or not... but I wanted to explain why if you debug
// you might seem some TypeError or ReferenceError items appear.
var result:* = bytes.readObject();
return result;
}
데이터 유형 "에 대한 의미 : 모든 당신이, 당신이 ByteArray의 트릭을 사용하여 바닐라 오브젝트의 강력한 타입의 객체를 생성 할 수 있습니다 만들 개체에 대한 사용자 정의 JSON 파서를 작성하는 것을 피하기 위해 사람"? –