简体   繁体   中英

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.

The Json is nested into a list and an object that have a 2ed tier list.

What i want is to insert this Josn into my local DB (Using 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. 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.

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.

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. 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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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