简体   繁体   English

Flutter 如何将嵌套的 JSON 数组插入到不同的 SQLite 表中

[英]Flutter How to insert nested JSON array into different SQLite tables

I hope I could explain clearly my need, What I have is an API that I connect to and recive a JSON from it.我希望我能清楚地解释我的需求,我拥有的是一个 API,我可以连接到它并从中接收 JSON。

The Json is nested into a list and an object that have a 2ed tier list. Json 嵌套在一个列表和一个具有 2ed 层列表的对象中。

What i want is to insert this Josn into my local DB (Using SQLite for Flutter).我想要的是将此 Josn 插入到我的本地数据库中(使用 SQLite for Flutter)。

The point I reached is the inserting of the 1st tier of the json data, but could not insert the data that exist as a list in the 2ed tier.我达到的点是插入 json 数据的第一层,但无法插入作为列表存在于 2ed 层中的数据。 Although I serilize it but the list after when i try to insert, have no mappnig from a list form to the database table fields.虽然我将它序列化,但是当我尝试插入之后的列表时,没有从列表表单到数据库表字段的映射。

Its like I have [Class User] and [Class Company] A user have many companies rolled in.就像我有 [Class User] 和 [Class Company] 一个用户有很多公司。

When serilaizing the data from the JSON I have the data come to the User Class then nesting to the Companies Class and do the serilaizng for the 2ed tier of the json object then return.当从 JSON 序列化数据时,我让数据进入用户类,然后嵌套到公司类,并为 json 对象的 2ed 层执行序列化,然后返回。

The next step is to insert the data into DB but the data I have in my last object is something like this:下一步是将数据插入数据库,但我在最后一个对象中的数据是这样的:

"username" : userName "company" : CompanyList --- This is a list and cant be inserted into the DB directly in a nested way. "username" : userName "company" : CompanyList --- 这是一个列表,不能以嵌套方式直接插入到数据库中。 As the companylist have multyble fields.由于公司列表有多个字段。 and more than one records ex: two companies.并且不止一个记录,例如:两家公司。

I belive there would be A map to do this in reverse so i could insert it to the DB (I have it in my Company Class) but i cant call it from the place where i try to insert the data into DB due of the differnce in the Classes instances我相信会有一张地图可以反向执行此操作,因此我可以将其插入数据库(我在我的公司类中有它),但由于差异,我无法从尝试将数据插入数据库的地方调用它在 Classes 实例中

The instance in my hand is a User Type instance [The main Class between the two], while the companyList if wanted to map it needs a Company insance type.我手上的实例是一个User Type实例[两者之间的主Class],而companyList如果要映射它需要一个Company实例类型。

I can provide code or explain more, any help or idea about the approach may help.我可以提供代码或解释更多,有关该方法的任何帮助或想法都可能有所帮助。 Thanks a lot!非常感谢!

#EDIT This where i try to insert the data into DB #EDIT 这是我尝试将数据插入数据库的地方

The first inserting is fine but the 2ed one is not.第一次插入很好,但第二次插入则不然。

  Future<int> createUserPermissions(UserPermissions userPermissions, ComListPermissions comListPermissions) async {
    final db = await dbProvider.database;
    var result = db.insert(userPermissionsDBTable, userPermissions.mapToDB());

    db.insert(userCompaniesTableDB, comListPermissions.toJson());
    return result;
  }

User Class用户类

class UserPermissions {
  final String userName;
  final  List<ComListPermissions> comLists;
  final bool active;

  final String groupName;
  final int companyId;
  final String permissions;
  final ComListPermissions company;

  UserPermissions({this.company, this.groupName, this.companyId, this.permissions, this.userName, this.active, this.comLists});

  factory UserPermissions.mapFromJsonToDB(Map<String, dynamic> data) {
    if (data['comLists'] != null) {
      var companyObjJson = data['comLists'] as List;

      List<ComListPermissions> _companies = companyObjJson
          .map((companyJson) => ComListPermissions.fromJson(companyJson))
          .toList();

      return UserPermissions(
        userName: data['userName'],
        active: data['active'],
        comLists: _companies,
      );
    } else {
      return UserPermissions(
        userName: data['userName'],
        active: data['active'],
      );
    }
  }

  Map<String, dynamic> mapToDB() => {
        "userName": userName,
       // "comLists": comLists,
        "active": active,
      };

}

Comapny Class公司班级

class ComListPermissions {
  ComListPermissions({
    this.groupName,
    this.companyId,
    this.permissions,
  });

  String groupName;
  int companyId;
  String permissions;
  //List<String> permissions;



  factory ComListPermissions.fromJson(Map<String, dynamic> json) {
    if (json['permissions'] != null) {
      var permissionsObjJson = json['permissions'] as List;
      String s = permissionsObjJson.toString();

      return ComListPermissions(
        groupName: json["groupName"],
        companyId: json["companyID"],
        permissions: s,
      );
    } else {
      return ComListPermissions(
        groupName: json["groupName"],
        companyId: json["companyID"],
      );
    }
  }

  Map<String, dynamic> toJson() => {
        "groupName": groupName,
        "companyID": companyId,
        "permissions": permissions,

    //"permissions": List<dynamic>.from(permissions.map((x) => x)),
      };
}

I Just added a for loop and sent index every time i needed to insert a new recırd into my DB我只是添加了一个 for 循环并在每次需要将新记录插入我的数据库时发送索引

  Future<int> createUserPermissions(UserPermissions userPermissions) async {
    final db = await dbProvider.database;
    var result = db.insert(userPermissionsDBTable, userPermissions.mapToDB());
    int index = userPermissions.comLists.length;
    for (int i = 0; i < index; i++) {
      db.insert(userCompaniesTableDB, userPermissions.toDatabaseForCompany(i));
    }
    return result;
  }
  Map<String, dynamic> toDatabaseForCompany(int index) => {
    "companyID": comLists[index].companyId,
    "groupName": comLists[index].groupName,
    "permissions": comLists[index].permissions,
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM