使用飞镖从 google 知识 API 访问嵌套的 JSON

Accessing nested JSON from google knowledge API with dart

如果之前有人问过这个问题,我很抱歉(我已经准确地搜索过了,但还是想不通)。我正在尝试从 google 知识图谱 API 访问嵌套元素。这是 JSON 的样子

{
  "@context": {
    "goog": "http://schema.googleapis.com/",
    "kg": "http://g.co/kg",
    "EntitySearchResult": "goog:EntitySearchResult",
    "resultScore": "goog:resultScore",
    "@vocab": "http://schema.org/",
    "detailedDescription": "goog:detailedDescription"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "name": "Samoyed",
        "description": "Dog breed",
        "@type": [
          "Thing"
        ],
        "@id": "kg:/m/017lg8",
        "detailedDescription": {
          "url": "https://en.wikipedia.org/wiki/Samoyed_dog",
          "articleBody": "The Samoyed is a breed of medium-sized herding dogs with thick, white, double-layer coats. They are a spitz-type dog which takes its name from the Samoyedic peoples of Siberia.",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        }
      },
      "@type": "EntitySearchResult",
      "resultScore": 7775.93505859375
    }
  ]
}

我需要访问 articleBody 元素。这是我到目前为止在飞镖中得到的:

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

  if (response.statusCode == 200) {
    for (var element in json.decode(response.body)['itemListElement']) {
      for (var subelement
          in json.decode(response.body)['detailedDescription']) {
        print(subelement['articleBody']);
      }
    }
  }

我一直在尝试对此进行不同的迭代以尝试 return 该元素。这是我的狗 Class 的样子。

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

  factory Dog.fromJson(Map<String, dynamic> json) {
    return Dog(
        breed: json['message'],
        link: json['message'],
        info: json['articleBody']);
  }
}

按照你的逻辑试试这个序列码

json.decode(response.body)["itemListElement"][0]["result"]["detailedDescription"]