如何在Map结构中使用fromJson将数据转换为List?
Hey there! Let's break this down based on what kind of Map you're working with. I'll cover the two most common scenarios I see when dealing with nested JSON structures and fromJson conversions.
If your JSON Map has a nested object that represents a single Gallery (like {"data": {"id": 1, "title": "My Vacation Gallery"}}), you just need to extract that nested JSON first, then pass it to your Gallery.fromJson constructor:
// Example JSON Map Map<String, dynamic> jsonMap = { "data": { "id": 1, "title": "Summer Getaway", "imageCount": 12 } }; // Extract the nested gallery JSON and convert it Gallery myGallery = Gallery.fromJson(jsonMap['data'] as Map<String, dynamic>);
The key here is accessing the correct key in your outer Map to get the inner JSON object that matches your Gallery's structure, then casting it to Map<String, dynamic> to keep Dart's type system happy.
If your Map has a list of Gallery JSON objects (like {"galleries": [{"id":1, ...}, {"id":2, ...}]}), you can extend the list conversion you already know by first extracting the array from the Map:
// Example JSON Map with a gallery array Map<String, dynamic> jsonMap = { "galleries": [ {"id": 1, "title": "Summer Getaway", "imageCount": 12}, {"id": 2, "title": "Winter Hikes", "imageCount": 8} ] }; // Extract the array, then map and convert each item List<Gallery> galleryList = (jsonMap['galleries'] as List) .map((galleryJson) => Gallery.fromJson(galleryJson as Map<String, dynamic>)) .toList();
This works exactly like the list conversion you're already familiar with—we just first pull the list out of the outer Map before running map and toList().
If your jsonMap itself is the full JSON structure for one Gallery (no nested keys), you can skip the key access and pass the whole Map directly:
Map<String, dynamic> jsonMap = { "id": 1, "title": "Summer Getaway", "imageCount": 12 }; Gallery myGallery = Gallery.fromJson(jsonMap);
Just remember to always cast the dynamic values to the correct type (Map<String, dynamic> for single objects, List for arrays) to avoid runtime errors—Dart's type system will thank you!
内容的提问来源于stack exchange,提问作者Wisit Phusi

