密钥嵌套数组和/或字典的Swift JSON对象

时间:2016-08-09 20:17:26

标签: 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")

[Not Pulling"定义"键] [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"
                                );

2 个答案:

答案 0 :(得分:0)

太深的嵌套是一种着名的不良做法,并且使用NSArray是违反类型安全的,并且您仍然在“安全代码”中使用了许多! s,这些都非常不安全。

你的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)
}

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

答案 1 :(得分:0)

func parse(data:NSData){         print(“使其成为常规解析函数”)

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

        if let dict = json["results"] as? [Dictionary<String,AnyObject>]{
            print("inside dict")

            if let lex = dict[0]["lexicalEntries"] as?[Dictionary<String,AnyObject>]{
                print("inside lex")

                if let entry = lex[0]["entries"] as? [Dictionary<String,AnyObject>]{

                    print("inside entry")

                    if let sense = entry[0]["senses"] {
                        print("inside sense")

                        if let define = sense[0]["definitions"] as? [String] {
                            print("inside define")

                            let def = define[0]
                            print("this is def")
                            print(def)

                            //self.hintLabel.text = "\(def)"
                            dispatch_async(dispatch_get_main_queue(), {
                                self.hintLabel.text = "\(def)"
                            })

                        }

                    }

                }
            }
        }

    } catch {
        print("error serializing JSON: \(error)")
        if hintLabel.text != "" && hintLabel.text != nil {
            self.hintLabel.text = "Sorry, a hint is not available for this word!"
        }

    } }