0

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<>?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

could i ask you one more? after decoding responseBody why [.map((item) => Photo(title: item.title))] is need? i thought just[ .toList() ]only need
jsonDecode and json.decode don't give you an object like javascript does , in this particular case it returns a List of Map<String,dynamic> , in your original code you mapped every object to a Photo object created from that json. In my case , i map every "item" to a Photo object as well , the difference is , i don't call a "fromJson" function, instead, i call the constructor , and then return a list of "Photo" .
1

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'],
    );
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.