【发布时间】:2020-06-02 19:52:52
【问题描述】:
我正在使用 dart 中的一些复杂 json,但在我知道它们将是什么类型之前创建对象时遇到了问题。
我很欣赏这些建议,但我认为我并不完全理解。在给定的答案中:
var entity = Model();
castToEntity(entity, {'test': 10});
我不需要知道它将是一个模型类吗? 如果我有以下两个类怎么办:
@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));
}
据说dart没有反射,所以我不知道还有什么办法。
【问题讨论】:
标签: json sqlite flutter dart sqflite