1

I am a student, and hoping I am using the correct terminology.

I need to get to the "descriptions" key in order to populate Label.text. I am able to Pull "results", but nothing else I was able to achieve this, but was getting a subscript error when i started usin 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!"
        }
    }

[original - This works and is pulling the "definitions" key][1]

So, I attempted Safety code leveraging the do/try methodology, but I am only pulling "results". I am having a problem drilling down to definitions. This snapshot is missing the synch, but I have omitted it.

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 "Definitions" key][2]


Dictionary is as follows

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"
                                );
  • I appreciate your help, and hope my question is not too confusing. – Natasha Cooks Aug 09 '16 at 20:18
  • Your "Dictionary is as follows" is incomplete and hard to reconstruct the original data. Showing the text representation of JSON would help readers to solve your issue. (Of course the number of results should be reduced...) – OOPer Aug 09 '16 at 21:57

2 Answers2

0

Too deep nesting is one of the famous bad practices, and using NSArray is against type safety, and you still use many !s in your "Safety code" which are really unsafe.

Your if-let can be written as something like this:

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

You should check if an Array has enough elements before getting an element with subscripts, as well as checking the non-nil result of subscripting to a Dictionary.

OOPer
  • 47,149
  • 6
  • 107
  • 142
0

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

    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!"
        }

    } }