我已经实现了将返回的JSON数据存储在本地数据库(SQFlite)中的代码。
我只想存储is_deleted
参数为0的那些数据。
我不确定如何实施。任何解决方案都会有很大帮助。
这是JSON:
"subject": [
{
"univ_spec_sub_id": "53",
"univ_year_sem_id": "18",
"sem_id": "2",
"university_id": "5",
"master_course_id": "36",
"subject_name": "Programming and Problem Solving",
"subject_desc": "99",
"info": "Programming and Problem Solving using Python",
"no_units": "6",
"is_deleted": "0",
},
{
"univ_spec_sub_id": "59",
"univ_year_sem_id": "18",
"sem_id": "2",
"university_id": "5",
"master_course_id": "37",
"subject_name": "Basic Electrical Engineering",
"subject_desc": "99",
"info": "",
"no_units": "100",
"is_deleted": "0",
},
{
"univ_spec_sub_id": "61",
"univ_year_sem_id": "18",
"sem_id": "2",
"university_id": "5",
"master_course_id": "38",
"subject_name": "Engineering Mathematics II",
"subject_desc": "99",
"info": "",
"no_units": "6",
"is_deleted": "0",
},
{
"univ_spec_sub_id": "65",
"univ_year_sem_id": "18",
"sem_id": "2",
"university_id": "5",
"master_course_id": "39",
"subject_name": "Engineering Graphics",
"subject_desc": "99",
"info": "",
"no_units": "6",
"is_deleted": "1",
}
],
我已经实现了以下代码,以将返回的JSON存储到本地数据库中。
Future<Semdata> semdata(String url, {Map body} ) {
return http.post(url,
body:body).then((http.Response response){
if (response.statusCode < 200 || response.statusCode > 400 || json == null) {
throw new Exception("Error while fetching data");
}
//JsonDecoder().convert(response.body);
var extractdata = json.decode(response.body);
List subdata = extractdata["subject"];
Map<String, dynamic> decodedData = json.decode(response.body);
for(Map<String, dynamic> subjectMap in decodedData['subject']){
print(subjectMap["subject"]["is_deleted"]);
if(subjectMap["subject"]["is_deleted"]== "0"){
db.savesubject(subjectMap);
}
// db.savesubject(subjectMap);
}
return Semdata.fromJson(json.decode(response.body));
});
}
答案 0 :(得分:1)
(重写我的回答,因为我认为我全都错了,我想我对json.decode(response.body)的多个相同调用感到困惑。)
这里我假设您还没有启动数据库...
一种解决方案是创建一个包含所有主题字段的表。在这里,我假设univ_spec_sub_id
是主键(唯一)。
var db =
await openDatabase(path, version: 1, onCreate: (db, version) async {
await db.execute('''
CREATE TABLE Subject (
univ_spec_sub_id TEXT PRIMARY KEY,
univ_year_sem_id TEXT,
sem_id TEXT,
university_id TEXT,
master_course_id TEXT,
subject_name TEXT,
subject_desc TEXT,
info TEXT,
no_units TEXT,
is_deleted TEXT);
''');
});
接收数据时,应对其进行解码,并保留带有'is_deleted'=='0'的项目,并在事务中将其添加到数据库中
// Decode the body
var responseData = jsonDecode(response.body) as Map;
// Only keep data with 'is_deleted' == '0' in a list
var subjects = (responseData['subject'] as List)
.map((raw) => (raw as Map)?.cast<String, dynamic>())
.where((map) => map['is_deleted'] == '0');
// Save subjects in a transaction
if (subjects.isNotEmpty) {
await db.transaction((txn) async {
for (var subjects in subjects) {
await txn.insert('Subject', subjects);
}
});
}