将JSON字符串反序列化为Haxe中的类实例

Cog*_*ave 5 json haxe deserialization

我试图将JSON字符串反序列化为Haxe中的类实例.

class Action
{
    public var id:Int;
    public var name:String;

    public function new(id:Int, name:String)
    {
        this.id = id;
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

var action:Action = haxe.Json.parse(actionJson);
trace(action.name);
Run Code Online (Sandbox Code Playgroud)

但是,这会产生错误:

TypeError:错误#1034:类型强制失败:无法将Object @ 3431809转换为Action

Fra*_*lli 4

Json 没有映射语言特定数据类型的机制,仅支持 JS 中包含的数据类型的子集。要保留有关 Haxe 类型的信息,您当然可以构建自己的机制。

// This works only for basic class instances but you can extend it to work with 
// any type.
// It doesn't work with nested class instances; you can detect the required
// types with macros (will fail for interfaces or extended classes) or keep
// track of the types in the serialized object.
// Also you will have problems with objects that have circular references.

class JsonType {
  public static function encode(o : Dynamic) {
    // to solve some of the issues above you should iterate on all the fields,
    // check for a non-compatible Json type and build a structure like the
    // following before serializing
    return haxe.Json.stringify({
      type : Type.getClassName(Type.getClass(o)),
      data : o
    });
  }

  public static function decode<T>(s : String) : T {
    var o = haxe.Json.parse(s),
        inst = Type.createEmptyInstance(Type.resolveClass(o.type));
    populate(inst, o.data);
    return inst;
  }

  static function populate(inst, data) {
    for(field in Reflect.fields(data)) {
      Reflect.setField(inst, field, Reflect.field(data, field));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)