我有这样的JSON代码:
final String response = await rootBundle.loadString('assets/Schools.json');
List data = await json.decode(response);
print(data);
/* output:
[{ "city": "ISTANBUL", "districty": "Kagithane", "name": "Kagithane anadolu lisesi"}, { "city": "ISTANBUL", "districty": "Sisli", "name": "Aziz Sancar anadolu lisesi"}, { "city": "IZMIR", "districty": "Adalar", "name": "Kemal Sunal anadolu lisesi"}, { "city": "ISTANBUL", "districty": "Bagcilar", "name": "Bagcilar Fen lisesi"}, { "city": "ISTANBUL", "districty": "Kagithane", "name": "Kagithane Meslek lisesi"}]
*/艾还写了这样一个模型:
List <School> schools = [];
List<School> allSchools() {
return schools;
}
class School {
String city;
String districty;
String name;
School({required this.city, required this.name, required this.districty});
}如何将数据从JSON导出到list?所以我想这样传递:
List <School> schools = [
School(city: "ISTANBUL", districty: "Kagithane", name: "Kagithane anadolu lisesi"),
School(city: "ISTANBUL", districty: "Sisli", name: "Aziz Sancar anadolu lisesi"),
School(city: "IZMIR", districty: "ADALAR", name: "Kemal Sunal anadolu lisesi"),
School(city: "ISTANBUL", districty: "BAGCILAR", name: "Bagcilar Fen lisesi"),
School(city: "ISTANBUL", districty: "Kagithane", name: "Kagithane Meslek lisesi")
];我感谢你提前帮忙,谢谢。
发布于 2022-12-03 17:34:08
正如@Spanching所说,工厂使用工厂是最好的方式,因为它是简单和有效的使用。
但是,由于您的问题包含了如何搜索特定的学校,我将在这里添加一些额外的提示。
首先,创建一个工厂构造函数:
class School {
String city;
String districty;
String name;
School({required this.city, required this.name, required this.districty});
factory School.fromJson(Map<String, dynamic> json) {
return School(
city: json['city'],
name: json['name'],
districty: json['district'],
);
}
}现在创建另一所班级来轻松地处理数据:
class Schools {
List<School> list;
Schools({required this.list});
factory Schools.fromJson(List<dynamic> json) {
return Schools(
list: json.map((e) => School.fromJson(e)).toList(),
);
}
}添加getter以获取类的实例:
static Future<Schools> get instance async {
final String response = await rootBundle.loadString('assets/Schools.json');
List data = await json.decode(response);
return Schools.fromJson(data);
}根据需要添加方法。例如,如果您想按城市搜索一所学校,可以添加如下方法:
List<School> searchByCity(String city) {
return list.where((element) => element.city == city).toList();
}现在,您的主程序甚至可以阅读如下:
final schools = await Schools.instance;
final schoolList = schools.searchByCity('ISTANBUL');
print(schoolList);那是很多代码,但我希望它能帮到你。如果您想了解整个代码,可以使用在这里查一下。
发布于 2022-12-03 16:45:28
您可以使用List.map()方法并传递一个函数,该函数从列表中的每个JSON对象创建一个School:
List data = json.decode(response);
schools = data.map((schoolData) => School(
city: schoolData['city'],
districty: schoolData['districty'],
name: schoolData['name']
)).toList();发布于 2022-12-03 16:47:11
你可以在你学校的班级里用这样的工厂:
factory School.fromJson(Map<String, dynamic> json) {
return School(city: json["city"], districty: json["districty"], name: json["name"]);
}然后从您的json中映射列表:
var schools = data.map((school) => School.fromJson(school)).toList();https://stackoverflow.com/questions/74668608
复制相似问题