json - 键嵌套数组和/或字典的 Swift JSON 对象

标签 json swift nsarray nsdictionary

我是一名学生,希望我使用的是正确的术语。

我需要使用“描述”键来填充 Label.text。我能够拉出“结果”,但没有别的 我能够做到这一点,但是当我开始使用 AVFoundation 时出现下标错误

do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves)

        let a1 = json["results"] as? [[String: AnyObject]]
        let a2 = a1![0]
        let a3 = a2["lexicalEntries"]
        let d1 = a3![0] as? [String: AnyObject]
        let d2 = d1!["entries"] as? [[String: AnyObject]]
        let a4 = d2![0]
        let d3 = a4["senses"] as? [[String: AnyObject]]
        let a5 = d3![0]
        let d4 = a5["definitions"] as? [String]
        let a6 = d4![0]
        dispatch_async(dispatch_get_main_queue(), {
            //self.wordLabel.text = a6 as String
            self.hintLabel.text = a6 as String
        })

        print(a6)

    } catch {
        print("error serializing JSON: \(error)")
        if wordLabel.text != "" && wordLabel.text != nil {
            self.wordLabel.text = "No hints for you!"
        }
    }

[原创 - 这有效并且正在拉动“定义”键][1]

因此,我尝试了利用 do/try 方法的安全代码,但我只是提取“结果”。我在深入定义时遇到问题。此快照缺少同步,但我已将其省略。

func parseTest(data: NSData) {


    do {
        //let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        //Not working
        let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        if let results = json["results"] as? [[String: AnyObject]] {
            print(" ResultsBegin \(results) ResultsEnd ")
            /*for result in results*/
            //if let mainDict = (json.objectForKey("results") as? NSArray?)! {
              //  print("mainDict \(mainDict) mainDict")
                if let lexEntry = (json.objectForKey("lexicalEntries") as? NSArray?)! {
                    print("lexEntry \(lexEntry) lexEntry")
                    if let entry = (json.objectForKey("entries") as? NSArray?)!{
                        print("entriesArray \(entry) entriesArray")
                        if let sense = (json.objectForKey("senses") as? NSArray?)! {
                            print("senseArray \(sense) senseArray")
                            if let definition = (json.objectForKey("definitions") as? NSArray?)! {
                                print("defArray \(definition) defArray")
                            }
                        }
                    }

                }


            dispatch_async(dispatch_get_main_queue(), {
                               //self.wordLabel.text = a6 as String
                 self.hintLabel.text = "Made it to Parse Test Function above catch"
                print("Made it to Parse Test Function above catch")
                            })
        }
    } catch {
        print("error serializing JSON: \(error)")
    }
    //print(" Parse Test \(def)")

        }
func parse(data: NSData) {
    print("Made it to Regular Parse Function")

[不拉“定义”键][2]


词典如下

results =     (
            {
        id = angular;
        language = en;
        lexicalEntries =             (
                            {
                entries =                     (
                                            {
                        etymologies =                             (
                            "late Middle English (as an astrological term): from Latin angularis, from angulus angle"
                        );
                        senses =                             (
                                                            {
                                definitions =                                     (
                                    "having angles or sharp corners"
                                );

最佳答案

太深的嵌套是著名的不良做法之一,使用 NSArray 违反类型安全,您仍然在“安全代码”中使用许多 !真的很不安全。

你的 if-let 可以这样写:

if
    let a1 = json["results"] as? [[String: AnyObject]] where !a1.isEmpty,
    case let a2 = a1[0],
    let a3 = a2["lexicalEntries"] as? [[String: AnyObject]] where !a3.isEmpty,
    case let d1 = a3[0],
    let d2 = d1["entries"] as? [[String: AnyObject]] where !d2.isEmpty,
    case let a4 = d2[0],
    let d3 = a4["senses"] as? [[String: AnyObject]] where !d3.isEmpty,
    case let a5 = d3[0],
    let d4 = a5["definitions"] as? [String] where !d4.isEmpty,
    case let a6 = d4[0]
{
    //...
    print(a6)
}

在获取带有下标的元素之前,您应该检查数组是否有足够的元素,以及检查下标到字典的非零结果。

关于json - 键嵌套数组和/或字典的 Swift JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859670/

相关文章:

ios - 从 ios 应用程序的 SWIFT 中的自定义单元格按钮转到另一个 View

ios - 获取 AFNetworking 响应的结果作为 JSON 字符串数组

ios - 由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因 : '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance

java - 以编程方式更改 LinearLayout 的背景颜色

c# - 将 JS 数组 = {} 发送到 C# (WebMethod)

php - .txt 写入 .json 文件批处理或需要 php 文件

java - JSON 对象扁平化为 CSV 一行

xcode - 使用 Swift,我似乎只有在使用 arc4random 时才会出现此错误。为什么,我该如何解决?

ios - 按顺序显示编辑的NSString

ios - 如何从 NSDictionary 数组中检查 boolean 值