如何访问嵌套在牛津字典API的数组和字典的多个级别中的定义键?

时间:2018-12-21 16:11:05

标签: json swift api dictionary

我是一名高中的iOS Swift应用程序开发班的学生。我正在尝试访问牛津英语词典API中的定义键,该键嵌套在多个数组和字典中。我已经访问了“ lexicalEntries”键中的数据,但无法在API中进行任何进一步的工作。

在尝试拆开数据时,我尝试了许多不同的方法,但没有一个起作用。注释掉了我尝试利用的一些技术,其中包括一些技术。

func parse() {
    let word_id = word.lowercased()
    let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/\(language)/\(word_id)")!
    //        let word = id
    //        let otherDefinitions = subsenses
    var request = URLRequest(url: url)
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue(appId, forHTTPHeaderField: "app_id")
    request.addValue(appKey, forHTTPHeaderField: "app_key")
    let session = URLSession.shared
    _ = session.dataTask(with: request, completionHandler: { data, response, error in
        if let response = response,
            let data = data,
            let jsonData = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject] {
            //                print(response)
            //                print(jsonData)
            //                print(jsonData["results"] as Any)
            //                print(jsonData["entries"] as Any) // does not work
            //

            let results = jsonData["results"] as? [JSONDictionary]
            // let entries = jsonData["entries"] as Any //does not work
            for result in results! {
                print(result)
            }
            //working through entries level
            //                let lexicalEntries = results?["lexicalEntries"] as? [String:String]
            //                print(lexicalEntries)
            //                let entries = jsonData["entries"] as Any
            //                let senses = jsonData["senses"] as Any
            //                let definitions = jsonData["definitions"] as Any
            //                print(entries)
        } else {
            print(error ?? print("default Value Called"))
            print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue)!)

        }
    }).resume()
}

在所有尝试期间,我唯一能够解析的嵌套数据是“ lexicalEntries”。我无法通过该点来访问API中的定义键。

API结构图: Picture of API Structure

1 个答案:

答案 0 :(得分:1)

如果您使用Swift 4或更高版本进行编码,则应使用Codable协议并构造API返回的数据。

struct Root: Codable {
    let metadata: Metadata
    let results: [Result]
}
struct Metadata: Codable {
    let provider: String
}
struct Result: Codable {
    let id: String
    let language: String
    let lexicalEntries: [Lexical]
}
struct Lexical: Codable {
    let entries: [Entry]
}
struct Entry: Codable {
    let etymologies: [String]?
    let grammaticalFeatures: [Feature]
    let homographNumber: String
    let senses: [Sense]
}
struct Feature: Codable {
    let text: String
    let type: String
}
struct Sense: Codable {
    let definitions: [String]
    let domains: [String]?
    let examples: [Example]
    let id: String
    let short_definitions: [String]
}
struct Example: Codable {
    let registers: [String]?
    let text: String
}

然后,您可以轻松解析JSON数据响应:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let wordId = "Ace"
let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/en/\(wordId)")!
let appId = "********"
let appKey = "********************************"
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8) ?? "")
    do {
        let root = try JSONDecoder().decode(Root.self, from: data)
        let results = root.results
        for result in results {
            for lexical in result.lexicalEntries {
                for entry in lexical.entries {
                    for sense in entry.senses {
                        for definition in sense.definitions {
                            print(definition)
                        }
                    }
                }
            }
        }
    } catch {
        print(error)
    }

}.resume()

这将打印

  

上面只有一个点的扑克牌,在大多数纸牌游戏中被评为其西装中最高的纸牌

     

在某项运动或其他活动中表现出色的人

     

(在网球和类似游戏中)对手无法返回并因此获得积分的服务。

     

没有性欲或性欲的人

     

非常好

     

(一个人)没有性欲或性欲,无性

     

(在网球和类似游戏中)在(对手)中获得王牌

     

(考试或考试)获得高分