gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:12:19 24 4
gpt4 key购买 nike

我正在尝试将 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;
}
}

我想做这样的事情:
var action:Action = haxe.Json.parse(actionJson);
trace(action.name);

但是,这会产生错误:

TypeError: Error #1034: Type Coercion failed: cannot convert Object@3431809 to Action

最佳答案

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));
}
}
}

关于json - 将 JSON 字符串反序列化为 Haxe 中的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com