我正在用dart处理一些复杂的json,在知道对象的类型之前,创建对象时遇到了问题。
我感谢这些建议,但我认为我并不完全理解。在给定的答案中:
var entity = Model();
castToEntity(entity, {'test': 10});
我不需要知道它将是Model类吗?如果我有以下两个课程,该怎么办:
@JsonSerializable(explicitToJson: true, includeIfNull: false)
class Location {
String id;
String resourceType;
Location({@required this.id, this.resourceType})
factory Location.fromJson(Map<String, dynamic> json) => _$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationToJson(this);
}
class Reference {
String reference;
String resourceType;
Location({@required this.reference, this.resourceType}
factory Reference.fromJson(Map<String, dynamic> json) => _$ReferenceFromJson(json);
Map<String, dynamic> toJson() => _$ReferenceToJson(this);
}
然后我查询服务器,但我不知道它将是什么样的类。它可以是位置,也可以是参考,或者如果是列表,则可以是两者的倍数,直到请求时我才知道。
var myBundle = Bundle.fromJson(json.decode(response.body));
每个“ myBundle.entry”是另一个资源。我希望能够使用该资源中的信息来定义自己。所以我可以做类似的事情:
myBundle.entry.resourceType newResource = new myBundle.entry.resourceType();
我现在正在做的是将其发送到已预定义所有可能选项的函数:
var newResource = ResourceTypes(myBundle.entry[i].resource.resourceType,
myBundle.entry[i].resource.toJson());
dynamic ResourceTypes(String resourceType, Map<String, dynamic> json) {
if (resourceType == 'Location') return (new Location.fromJson(json));
if (resourceType == 'Reference') return (new Reference.fromJson(json));
}
据说飞镖上没有反射,所以我不知道其他方法。
abstract class Serializable {
void fromJson(Map<String,dynamic> data);
}
class Model implements Serializable {
int test;
@override
void fromJson(data) {
test = data['test'];
}
}
Serializable castToEntity(Serializable entity, Map<String, dynamic> data) {
return entity..fromJson(data);
}
现在,当您阅读数据库并拥有Map时,可以调用类似以下方法的通用方法:
var entity = Model();
castToEntity(entity, {'test': 10});
print(entity.test);
其中实体是空模型。
注意:您在实体上的字段是最终的,因为
fromJson是实例方法而不是工厂方法。