我扩展了Franco 的答案,以允许在您的 json 对象中递归地包含对象,只要_explicitType
在该对象上设置了该属性。
例如,以下 json:
{
intPropertyExample : 5,
stringPropertyExample : 'my string',
pointPropertyExample : {
_explicitType : 'flash.geom.Point',
x : 5,
y : 6
}
}
将正确地序列化为类如下所示的对象:
import flash.geom.Point;
class MyTestClass
{
public var intPropertyExample:Int;
public var stringPropertyExample:String;
public var pointPropertyExample:Point;
}
打电话时:
var serializedObject:MyTestClass = EXTJsonSerialization.decode([string of json above], MyTestClass)
这是代码(请注意,它使用TJSON作为解析器,正如CrazySam推荐的那样):
import tjson.TJSON;
class EXTJsonSerialization
{
public static function encode(o : Dynamic)
{
return TJSON.encode(o);
}
public static function decode<T>(s : String, typeClass : Class<Dynamic>) : T
{
var o = TJSON.parse(s);
var inst = Type.createEmptyInstance(typeClass);
EXTJsonSerialization.populate(inst, o);
return inst;
}
private static function populate(inst, data)
{
for (field in Reflect.fields(data))
{
if (field == "_explicitType")
continue;
var value = Reflect.field(data, field);
var valueType = Type.getClass(value);
var valueTypeString:String = Type.getClassName(valueType);
var isValueObject:Bool = Reflect.isObject(value) && valueTypeString != "String";
var valueExplicitType:String = null;
if (isValueObject)
{
valueExplicitType = Reflect.field(value, "_explicitType");
if (valueExplicitType == null && valueTypeString == "Array")
valueExplicitType = "Array";
}
if (valueExplicitType != null)
{
var fieldInst = Type.createEmptyInstance(Type.resolveClass(valueExplicitType));
populate(fieldInst, value);
Reflect.setField(inst, field, fieldInst);
}
else
{
Reflect.setField(inst, field, value);
}
}
}
}