【问题标题】:Dynamic List in Flutter for JsonFlutter for Json 中的动态列表
【发布时间】: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


    【解决方案1】:

    据我所知,这是不可能的,因为 Dart 没有像 c# 那样的 Reflection,我能想象的最接近的,是使用一个抽象类来强制你的实体实现 fromJson,并且,在该方法,您读取 Map 并将值放入字段中,如下面的代码:

    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 是实例方法而不是工厂方法。

    【讨论】:

    • 让你所有的实体都实现那个接口,你也可以把“toJson”方法放在那个接口中......
    猜你喜欢
    • 2019-09-02
    • 2021-07-18
    • 2020-06-10
    • 1970-01-01
    • 2021-12-11
    • 2021-11-05
    • 1970-01-01
    • 2021-07-02
    • 2021-08-22
    相关资源
    最近更新 更多