json - 在 Swift 3 中获取 JSON 元素

标签 json swift3

如果这是一个简单的问题,请原谅我,但我被困住了。我尝试阅读所有能读到的东西来自己解决这个问题。

我正在尝试从 JSON 数据中提取 URL,我得到了 JSON 数据,并且可以将其打印到控制台,但是我无法弄清楚如何访问音频文件的 URL。

这是我用来获取 JSON 的代码:

 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: .mutableContainers) {

            if let dictionary = jsonData as? [String: Any] {
                if let prounce = dictionary["pronunciations"] as? [String: Any]{
                    if let audioPath = prounce["audioFile"] as? String {
                        print(audioPath)
                    }

                }
            }

            print(response)
            print(jsonData)
        } else {
            print(error)
            print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue))
        }
    }).resume()

我得到的输出是:

metadata =     {
    provider = "Oxford University Press";
};
results =     (
            {
        id = maladroit;
        language = en;
        lexicalEntries =             (
                            {
                entries =                     (
                                            {
                        etymologies =                             (
                            "late 17th century: French"
                        );
                        grammaticalFeatures =                             (
                                                            {
                                text = Positive;
                                type = Degree;
                            }
                        );
                        senses =                             (
                                                            {
                                definitions =                                     (
                                    "inefficient or inept; clumsy:"
                                );
                                examples =                                     (
                                                                            {
                                        text = "both men are unhappy about the maladroit way the matter has been handled";
                                    }
                                );
                                id = "m_en_gb0494140.001";
                            }
                        );
                    }
                );
                language = en;
                lexicalCategory = Adjective;
                pronunciations =                     (
                                            {
                        audioFile = "http://audio.oxforddictionaries.com/en/mp3/maladroit_gb_1.mp3";
                        dialects =                             (
                            "British English"
                        );
                        phoneticNotation = IPA;
                        phoneticSpelling = "\U02ccmal\U0259\U02c8dr\U0254\U026at";
                    }
                );
                text = maladroit;
            }
        );
        type = headword;
        word = maladroit;
    }
);

}

我想获取发音中名为 audioFile 的 URL。任何帮助深表感谢。

最佳答案

如果我的猜测是正确的,上面显示的输出在输出顶部缺少左大括号 {

(我还假设输出取自您的 print(jsonData)。)

您的 jsonData 是一个包含两个值的字典:

  • “元数据”的字典值
  • “结果”的数组值

因此,您无法直接从 jsonData (或 dictionary)检索“发音”的值。

您可能需要:

  • jsonData 中检索“results”的值,它是一个数组
  • 从“结果”中选择一个元素,它是一个字典
  • 从结果中检索“lexicalEntries”的值,它是一个数组
  • 从“lexicalEntries”中选择一个元素,它是一个字典
  • 从 lexicalEntry 中检索“发音”的值,它是一个数组
  • 从“发音”中选择一个元素,它是字典

在这里,您可以访问每个发音词典中的值。在代码中,您需要执行以下操作:

if
    let dictionary = jsonData as? [String: Any],
    let results = dictionary["results"] as? [[String: Any]],
    //You need to choose one from "results"
    !results.isEmpty, case let result = results[0],
    let lexicalEntries = result["lexicalEntries"] as? [[String: Any]],
    //You need to choose one from "lexicalEntries"
    !lexicalEntries.isEmpty, case let lexicalEntry = lexicalEntries[0],
    let pronunciations = lexicalEntry["pronunciations"] as? [[String: Any]],
    //You need to choose one from "lexicalEntries"
    !pronunciations.isEmpty, case let pronunciation = pronunciations[0]
{
    //Here you can use `pronunciation` as a Dictionary containing "audioFile" and some others...
    if let audioPath = pronunciation["audioFile"] as? String {
        print(audioPath)
    }
}

(如果您始终使用第一个元素,则可以使用 let result = results.first 代替 !results.isEmpty, case let result = results[0]对于数组。另外两行也从 !...isEmpty, case let... 开始。)

需要从最外层元素一步步深入到目标元素。

关于json - 在 Swift 3 中获取 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163727/

相关文章:

android - 从 Gson 更改为 Jackson 进行 JSON 解析

swift - 如何在 UI 测试中将照片添加到模拟器的相机胶卷中

swift - Swift 中的快速排序出错

swift - 在那里工作怎么样?

core-data - 核心数据: How to write "generic" fetch/delete function in swift 3?

javascript - 如何在 Laravel 中路由到 JSON 文件?

java - 如何在java中的azure中的父目录下添加子目录?

ios - 如何在 Swift 3 中使用 NSSecureCoding 解码字符串?

javascript - 从 json 中的 highchart 读回图表详细信息

java - 为不同类型的对象反序列化 JSON 数据