【问题标题】:Swift JSON Object for Key Nested Arrays and/or Dictionaries用于键嵌套数组和/或字典的 Swift JSON 对象
【发布时间】:2016-08-09 20:17:26
【问题描述】:

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

我需要使用“描述”键来填充 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"
                                );

【问题讨论】:

  • 感谢您的帮助,希望我的问题不会太混乱。
  • 您的“字典如下”不完整,很难重建原始数据。显示 JSON 的文本表示将帮助读者解决您的问题。 (当然应该减少结果的数量……)

标签: json swift nsarray nsdictionary


【解决方案1】:

嵌套太深是著名的不良做法之一,使用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)
}

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

【讨论】:

  • 我现在正在尝试这个。谢谢!
  • 只是跟进 - 您为我指明了正确的方向,在我的导师的帮助下,我得以运行!
【解决方案2】:

func 解析(数据: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!"
        }

    } }

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多