【发布时间】:2021-12-29 14:34:05
【问题描述】:
很抱歉,如果以前有人问过这个问题(我已经准确地搜索过这个问题,但仍然无法弄清楚)。我正在尝试从谷歌知识图 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 元素。这是我到目前为止在 dart 中得到的:
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']);
}
}
}
我一直在尝试不同的迭代来尝试返回该元素。这是我的 Dog 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"]
-
非常感谢!
-
很高兴为您提供帮助,如果有效,请标记upvote 并作为答案。谢谢
标签: json flutter api dart google-api