首页 > 解决方案 > 需要帮助在 SWIFT 中解析 wikipedia json api

问题描述

下面是一个 WIKI 页面的 json。(格式可能很差,所以这里有一个更好看的链接:https ://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=John_F._Kennedy&pithumbsize=500 )

{ "batchcomplete": "", "query": { "normalized": [ { "from": "John_F._Kennedy", "to": "John F. Kennedy" } ], "pages": { "5119376" : { "pageid": 5119376, "ns": 0, "title": "John F. Kennedy", "thumbnail": { "source": " https://upload.wikimedia.org/wikipedia/commons/thumb /5/5e/John_F._Kennedy%2C_White_House_photo_portrait%2C_looking_up.jpg/385px-John_F._Kennedy%2C_White_House_photo_portrait%2C_looking_up.jpg", "宽度": 385, "高度": 500 }, "页面图像": "John_F._Kennedy,_White_House_photo_portrait,_looking_up.jpg" } } } }

我用我的结构来表示 json 键,但我不知道我可以写什么结构或 var 来表示数字 5119376,这显然是一个对象。所有其他键值都是字符串并且不会更改。但是这个键很奇怪,因为它是一个整数,并且它会从 wiki 页面更改为 wiki 页面。所以我不知道该键的名称是什么,因为它应该是一个数字并且它随每一页而变化。

我尝试打印出整个对象以查看它在控制台中的外观:

{ WikiStruct(query: quote_project.QueryStruct(pages: Optional(quote_project.PageStruct(pageid: nil, ns: nil, title: nil, thumbnail: nil, pageimage: nil))), batchcomplete: Optional("")) }

所以计算机得到了“batchcomplete 是一个空字符串”,它还获取了规范化的东西。但它说奇怪的 5119376 对象内的所有内容都是 nil。顺便说一下,我的最终目标是访问给出 wiki 页面的主要 jpg 图像

我得到的错误是这样的:

 Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

我的结构如下。我尝试忽略 5119376 对象并尝试为其创建某种结构,但无济于事

struct WikiStruct: Decodable {

var query: QueryStruct
var batchcomplete: String?

}

struct QueryStruct: Decodable {

var normalized: [NormalizedStruct]?
var pages: PageStruct?

}

struct NormalizedStruct: Decodable{

var from: String?
var to: String?
}

struct PageStruct: Decodable{

var pageid: Int?
var ns: Int?
var title: String?
var thumbnail: ThumbStruct?
var pageimage: String?

}

struct ThumbStruct: Decodable{

var source: String?//this is what I want
var width: Int?
var height: Int?

}

标签: jsonswiftapiuiimageviewwikipedia-api

解决方案


今天有这个完全相同的问题。设法解决它。基本上,嵌套在 pages 下的数据是一个键控对象,键是 5119376。要解析它,只需将 QueryStruct 中的 pages 变量更改为字典。像这样:

struct QueryStruct: Decodable {

var normalized: [NormalizedStruct]?
var pages: [String:PageStruct]?

}

在此之后,我能够成功解析对象。WikiStruct 对象的打印:

WikiStruct(query: QueryStruct(normalized: [NormalizedStruct(from: "John_F._Kennedy", to: "John F. Kennedy")], pages: ["5119376": PageStruct(pageid: 5119376, ns: 0, title: "John F. Kennedy", thumbnail: ThumbStruct(source: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/John_F._Kennedy%2C_White_House_color_photo_portrait.jpg/385px-John_F._Kennedy%2C_White_House_color_photo_portrait.jpg", width: 385, height: 500), pageimage: "John_F._Kennedy,_White_House_color_photo_portrait.jpg")]), batchcomplete: "")


推荐阅读