You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中访问嵌套于JSON对象内的JSON数组?(Flutter歌词应用Genius API开发问题)

Fixing the Genius API Data Fetch Issue in Flutter

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 response object from the API's root data, then grab the hits array from that nested object.
  • For each entry in hits, we pull out the result field (which contains all the song metadata) and pass that to Songs.fromJson, so your factory method can access the correct keys like title and artist_names directly.

Give this a try, and you should be able to fetch the song data properly!

内容的提问来源于stack exchange,提问作者anish747

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:27:41