Парсинг сложного json flutter
Помогите разобраться с парсингом сложного json файла
"count": 82,
"next": "http://swapi.dev/api/people/?page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.dev/api/planets/1/",
"films": [
"http://swapi.dev/api/films/1/",
"http://swapi.dev/api/films/2/",
"http://swapi.dev/api/films/3/",
"http://swapi.dev/api/films/6/"
],
"species": [],
"vehicles": [
"http://swapi.dev/api/vehicles/14/",
"http://swapi.dev/api/vehicles/30/"
],
"starships": [
"http://swapi.dev/api/starships/12/",
"http://swapi.dev/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.dev/api/people/1/"
}
]
}
Код на flutter:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Character>> fetchCharacters(http.Client client) async {
final response =
await client.get('http://swapi.dev/api/people/');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseCharacter, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Character> parseCharacter(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Character>((json) => Character.fromJson(json)).toList();
}
class Character {
final String name;
final int height;
final int mass;
final String hairColor;
final String skinColor;
Character({this.name, this.height, this.mass, this.hairColor, this.skinColor});
factory Character.fromJson(Map<String, dynamic> json) {
return Character(
name: json['name'] as String,
height: json['height'] as int,
mass: json['mass'] as int,
hairColor: json['hair_color'] as String,
skinColor: json['skin_color'] as String,
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Character>>(
future: fetchCharacters(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(character: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Character> character;
PhotosList({Key key, this.character}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: character.length,
itemBuilder: (context, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Container(
padding: EdgeInsets.all(15),
child: ListTile(
title: Text(
character[index].name,
style: TextStyle(fontSize: 18, color: Colors.black),
),
onTap: () {},
),
),
);
},
);
}
}
Вопрос в том, как мне исправить код, чтобы брать данные из запроса, начиная с массива "results":
Ответы (1 шт):
Автор решения: MiT
→ Ссылка
List<Character> parseCharacter(String responseBody) {
final parsed = jsonDecode(responseBody) as Map<String, dynamic>;
return parsed["results"].map<Character>((json) => Character.fromJson(json)).toList();
}
class Character {
Character({
this.name,
this.height,
this.mass,
this.hairColor,
this.skinColor,
this.eyeColor,
this.birthYear,
this.gender,
this.homeworld,
this.films,
this.species,
this.vehicles,
this.starships,
this.created,
this.edited,
this.url,
});
final String name;
final String height;
final String mass;
final String hairColor;
final String skinColor;
final String eyeColor;
final String birthYear;
final String gender;
final String homeworld;
final List<String> films;
final List<dynamic> species;
final List<String> vehicles;
final List<String> starships;
final DateTime created;
final DateTime edited;
final String url;
factory Character.fromJson(Map<String, dynamic> json) => Character(
name: json["name"] == null ? null : json["name"],
height: json["height"] == null ? null : json["height"],
mass: json["mass"] == null ? null : json["mass"],
hairColor: json["hair_color"] == null ? null : json["hair_color"],
skinColor: json["skin_color"] == null ? null : json["skin_color"],
eyeColor: json["eye_color"] == null ? null : json["eye_color"],
birthYear: json["birth_year"] == null ? null : json["birth_year"],
gender: json["gender"] == null ? null : json["gender"],
homeworld: json["homeworld"] == null ? null : json["homeworld"],
films: json["films"] == null ? null : List<String>.from(json["films"].map((x) => x)),
species: json["species"] == null ? null : List<dynamic>.from(json["species"].map((x) => x)),
vehicles: json["vehicles"] == null ? null : List<String>.from(json["vehicles"].map((x) => x)),
starships: json["starships"] == null ? null : List<String>.from(json["starships"].map((x) => x)),
created: json["created"] == null ? null : DateTime.parse(json["created"]),
edited: json["edited"] == null ? null : DateTime.parse(json["edited"]),
url: json["url"] == null ? null : json["url"],
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
"height": height == null ? null : height,
"mass": mass == null ? null : mass,
"hair_color": hairColor == null ? null : hairColor,
"skin_color": skinColor == null ? null : skinColor,
"eye_color": eyeColor == null ? null : eyeColor,
"birth_year": birthYear == null ? null : birthYear,
"gender": gender == null ? null : gender,
"homeworld": homeworld == null ? null : homeworld,
"films": films == null ? null : List<dynamic>.from(films.map((x) => x)),
"species": species == null ? null : List<dynamic>.from(species.map((x) => x)),
"vehicles": vehicles == null ? null : List<dynamic>.from(vehicles.map((x) => x)),
"starships": starships == null ? null : List<dynamic>.from(starships.map((x) => x)),
"created": created == null ? null : created.toIso8601String(),
"edited": edited == null ? null : edited.toIso8601String(),
"url": url == null ? null : url,
};
}