下面是一个例子:
import 'dart:convert';
class Car {
final String make;
final String model;
Car({
required this.make,
required this.model,
});
factory Car.fromMap(Map<String, dynamic> map) => Car(
make: map['make'] as String,
model: map['model'] as String,
);
@override
String toString() => 'Car(make: $make, model: $model)';
}
class CelebrityProfile {
final String name;
final String yob;
final List<Car> carList;
CelebrityProfile({
required this.name,
required this.yob,
required this.carList,
});
factory CelebrityProfile.fromMap(Map<String, dynamic> map) =>
CelebrityProfile(
name: map['Name'] as String,
yob: map['YOB'] as String,
carList: [
for (final subMap in map['CarList'])
Car.fromMap(subMap as Map<String, dynamic>)
],
);
@override
String toString() =>
'CelebrityProfile(name: $name, yob: $yob, carList: $carList)';
}
void main() {
const jsonInput = '''{
"CelebrityProfile": [
{
"Name": "Celeb_1",
"YOB": "2000",
"CarList": [
{
"make": "Lamborghini",
"model": "Aventador SVJ"
},
{
"make": "Ferrari",
"model": "F8 Spider"
}
]
},
{
"Name": "Celeb_2",
"YOB": "1995",
"CarList": [
{
"make": "Tesla",
"model": "S"
},
{
"make": "Porsche",
"model": "911"
},
{
"make": "Lamborghini",
"model": "Huracan EVO"
}
]
}
]
}
''';
final parsedJson = jsonDecode(jsonInput) as Map<String, dynamic>;
final celebrityProfiles = [
for (final celebrityProfileMap in parsedJson['CelebrityProfile'])
CelebrityProfile.fromMap(celebrityProfileMap as Map<String, dynamic>)
];
celebrityProfiles.forEach(print);
// CelebrityProfile(name: Celeb_1, yob: 2000, carList: [Car(make: Lamborghini, model: Aventador SVJ), Car(make: Ferrari, model: F8 Spider)])
// CelebrityProfile(name: Celeb_2, yob: 1995, carList: [Car(make: Tesla, model: S), Car(make: Porsche, model: 911), Car(make: Lamborghini, model: Huracan EVO)])
}