flutter解析json参考

参考的2段代码 https://flutter.dev/docs/cookbook/networking/background-parsing

First, create a Photo class that contains data about a photo. Include a fromJson() factory method to make it easy to create a Photo starting with a JSON object.

 
class Photo {
  final int id;
  final String title;
  final String thumbnailUrl;

  Photo({this.id, this.title, this.thumbnailUrl});

  factory Photo.fromJson(Map<String, dynamic> json) {
    return Photo(
      id: json[‘id‘] as int,
      title: json[‘title‘] as String,
      thumbnailUrl: json[‘thumbnailUrl‘] as String,
    );
  }
}

Convert the response into a list of photos

Now, use the following instructions to update the fetchPhotos() function so that it returns a Future<List<Photo>>:

  1. Create a parsePhotos() function that converts the response body into a List<Photo>.
  2. Use the parsePhotos() function in the fetchPhotos() function.
 
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response =
      await client.get(‘https://jsonplaceholder.typicode.com/photos‘);

  return parsePhotos(response.body);
}

flutter解析json参考

上一篇:HTML学习4


下一篇:jquery: sand picture