如何在Dart中访问嵌套于JSON对象内的JSON数组?(Flutter歌词应用Genius API开发问题)
Hey there! Let's break down why you're not able to access the hits array and song data correctly. I spot two key issues in your code that are causing the problem:
1. Incorrect JSON Path to hits
Looking at the API response structure you shared, the hits array is nested inside the response object, not directly under the root data. Your current code tries to access response.data['hits'] directly, which skips the outer response layer entirely.
2. Wrong Data Source for Songs.fromJson
Each entry in the hits array wraps the actual song details in a result object. Your current code passes the entire hit object to Songs.fromJson, but you need to target the result sub-object instead to access fields like title or artist_names.
Corrected Code
Let's update your getData method first:
Future<List<Songs>> getData() async { Dio dio = Dio(); try{ final response = await dio.get('https://genius.p.rapidapi.com/search', queryParameters: {'q': 'Blackpink'}, options: Options(headers: { 'X-RapidAPI-Host': 'genius.p.rapidapi.com', 'X-RapidAPI-Key': 'bf5ec94953msh94dc7db178f218cp1f29f2jsn7e7fdfb01965' })); // Step 1: Access the outer "response" object first final hits = response.data['response']['hits'] as List; // Step 2: Map each hit's "result" sub-object to a Songs instance final data = hits.map((hit) => Songs.fromJson(hit['result'])).toList(); return data; } on DioError catch (err) { print(err); return []; } }
Your Songs.fromJson factory method is already aligned with the result object structure, so no changes are needed there—but let's confirm it matches:
factory Songs.fromJson(Map<String, dynamic> json) { return Songs( title: json['title'], url: json['url'], artist: json['artist_names'], imageUrl: json['song_art_image_url'], ); }
Why This Works
- We first extract the
responseobject from the API's root data, then grab thehitsarray from that nested object. - For each entry in
hits, we pull out theresultfield (which contains all the song metadata) and pass that toSongs.fromJson, so your factory method can access the correct keys liketitleandartist_namesdirectly.
Give this a try, and you should be able to fetch the song data properly!
内容的提问来源于stack exchange,提问作者anish747

