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

使用Dart获取谷歌知识图谱API嵌套JSON的articleBody字段方法

问题解决方法

核心错误原因

  • JSON层级访问错误:detailedDescription 不属于根节点,完整路径为 根对象 > itemListElement 数组元素 > result 对象 > detailedDescription 对象,且该字段是对象类型而非数组,不需要嵌套循环遍历
  • 重复解码响应体:无需多次调用json.decode(response.body),单次解码后存入变量复用即可
  • Dog 数据类解析逻辑不匹配:API 响应中不存在message字段,需按照返回结构做字段映射

修正后代码

1. Dog 数据类

class Dog {
  final String link;
  final String breed;
  final String info;
  Dog({required this.link, required this.breed, required this.info});

  // 直接传入接口返回的result节点JSON数据做解析
  factory Dog.fromKgJson(Map<String, dynamic> resultJson) {
    final detailedDesc = resultJson['detailedDescription'] as Map<String, dynamic>;
    return Dog(
      breed: resultJson['name'] as String,
      link: detailedDesc['url'] as String,
      info: detailedDesc['articleBody'] as String,
    );
  }
}

2. 请求与解析逻辑

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Dog?> getWikiInfo() async {
  var query = "Samoyed";
  var apiKey = "替换为你的API_KEY";
  final apiURL =
      "https://kgsearch.googleapis.com/v1/entities:search?query=$query&key=$apiKey&limit=1&indent=True";
  final response = await http.get(Uri.parse(apiURL));

  if (response.statusCode == 200) {
    // 单次解码响应体
    final Map<String, dynamic> responseData = json.decode(response.body);
    // 取itemListElement数组
    final List<dynamic> itemList = responseData['itemListElement'] as List;
    if (itemList.isNotEmpty) {
      // 取第一个元素的result节点
      final Map<String, dynamic> result = itemList.first['result'] as Map<String, dynamic>;
      // 解析成Dog对象返回
      return Dog.fromKgJson(result);
    }
  }
  // 请求失败或无结果时返回null
  return null;
}

3. 调用示例

Dog? samoyedInfo = await getWikiInfo();
if (samoyedInfo != null) {
  print("犬种:${samoyedInfo.breed}");
  print("介绍:${samoyedInfo.info}");
  print("维基链接:${samoyedInfo.link}");
}

可选兼容优化

如果需要适配API返回结果中不存在detailedDescription的场景,可以调整解析逻辑做判空处理:

factory Dog.fromKgJson(Map<String, dynamic> resultJson) {
  final detailedDesc = resultJson['detailedDescription'] as Map<String, dynamic>?;
  return Dog(
    breed: resultJson['name'] as String? ?? '未知犬种',
    link: detailedDesc?['url'] as String? ?? '',
    info: detailedDesc?['articleBody'] as String? ?? '暂无介绍',
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:07