evergreen
evergreen

Reputation: 763

parse json in flutter with map type

i don't understand how parse json to list or any types in flutter

https://jsonplaceholder.typicode.com/photos <= this is json example what i use

and that info is surrounded by [], {}

final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
  List<Photo> simple =
      parsed.map<Photo>((json) => Photo.fromJson(json)).toList();

i expect when json.decode.cast() work, parsed contain each objects but when i print parsed, it's just one array like [~~~] why they use cast method with Map<>?

Upvotes: 0

Views: 955

Answers (2)

sfung3
sfung3

Reputation: 2387

You do not need to cast the array because they are already a list of objects.

You can use the following to get a list of photo objects:

Future<String> getPhotos() async {
  var response = await http.get(
      'https://jsonplaceholder.typicode.com/photos');
  if (response.statusCode == 200) {
    var parsed = json.decode(response.body);
      List<Photo> simple = parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
      print(simple);
  }
}

This is the photo class used.

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

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

  factory Photo.fromJson(Map<dynamic, dynamic> json) {
    return Photo(albumId: json['albumId'],
      id: json['id'],
      title: json['title'],
      url: json['url'],
      thumbnailUrl: json['thumbnailUrl'],
    );
  }
}

Upvotes: 1

RegularGuy
RegularGuy

Reputation: 3686

jsonDecode already gives you the list object, so you can optimize the code.

In your case , instead of using

final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
  List<Photo> simple =
      parsed.map<Photo>((json) => Photo.fromJson(json)).toList();

try using

final List<Photo> simple = jsonDecode(responseBody).map((item) => Photo(title: item.title)).toList()

and you avoid having a fromJson function

Upvotes: 1

Related Questions