1

I am brand new to using JSON and wanted to get started with a simple app to provide a movie overview when you type in a title. My below code returns everything in one big string. How do I get just one piece of information like the overview or year?

With my below attempt, print(obj["overview"] as Any)) prints "nil" and print(obj) looks like this:

{
page = 1;
results =     (
            {
        adult = 0;
        "backdrop_path" = "/A0aGxrCGRBuCrDltGYiKGeAUect.jpg";
        "genre_ids" =             (
            53,
            80
        );
        id = 680;
        "original_language" = en;
        "original_title" = "Pulp Fiction";
        overview = "A burger-loving hit man, his philosophical partner, a drug-addled gangster's moll and a washed-up boxer converge in this sprawling, comedic crime caper. Their adventures unfurl in three stories that ingeniously trip back and forth in time.";

Current Code:

    let query = "Pulp+Fiction"
    let urlString = "https://api.themoviedb.org/3/search/movie?api_key={MYAPIKEY}&query=\(query)"

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print(error as Any)
        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!) as Any
                if let obj = parsedData as? NSDictionary {

                    print(obj["overview"] as Any)
                    print(obj)

                }
            } catch {
                print("error")
            }            }
        }.resume()
}
user4812000
  • 1,033
  • 1
  • 13
  • 24
  • 1
    Start with [these search results](https://stackoverflow.com/search?q=%5Bswift%5D+parse+json). – rmaddy May 11 '18 at 04:33
  • See [Apple's article](https://developer.apple.com/swift/blog/?id=37) on the subject. – rmaddy May 11 '18 at 04:34
  • Thank you for the links, but I should elaborate. I have reviewed these articles and i am still having trouble applying them to my code above, due to my lack of experience. – user4812000 May 11 '18 at 04:38
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – Pranavan SP May 11 '18 at 04:45
  • OK, now we are getting somewhere. You are crashing on the forced-cast to `[String: Any]`. This means that the value for `parsedData["title"]` is not a dictionary. Do not use any `as!` when parsing JSON. In order for anyone to help you further you need to show a relevant excerpt of the JSON result you are attempting to parse. Please put that (as text) in your question. – rmaddy May 11 '18 at 04:59
  • I was assuming that it is trying to tell me that "title" does not exist, but this is an example of what the site shows: {"page":1,"total_results":2,"total_pages":1,"results":[{"vote_count":3470,"id":75780,"video":false,"vote_average":6.4,"title":"Jack Reacher","popularity":12.963443, – user4812000 May 11 '18 at 05:02
  • 1
    Please learn to read JSON, it's very simple: `{}` is dictionary, `[]` is array. So the value for key `title` is clearly in an **array** for key `results` in the root dictionary. – vadian May 11 '18 at 05:07
  • It is clear for someone familiar with JSON. As I said, I am new to this and looking for guidance. How would you suggest I fix my above code? – user4812000 May 11 '18 at 05:09

2 Answers2

2
    // write this extension anywhere in your any swift file
    extension String{
         func toDictionary() -> NSDictionary {
          let blankDict : NSDictionary = [:]
         if let data = self.data(using: .utf8) {
            do {
               return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
                       } catch {
                            print(error.localizedDescription)
                        }
                    }
                    return blankDict
                }
            }
      //now  in your code modify as 
        if  data != nil {
                        let responseString = String(data: data!, encoding: .utf8)!
                        if(responseString != "")
                        {
                         //convert response string into dictionary using extended method
                         let responseValues = responseString.toDictionary()
                         //access value using keyPath using
                         let value = responseValues.value(forKeyPath: "key.key2")
//where key2 is the target key which is inside the value of key 
                     }
        }
Vivek Kumar
  • 405
  • 5
  • 15
0

First of all JSON results are never Any. As already mentioned in the comments the root object is a dictionary

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any],

The key overview is in array for key results

   let results = parsedData["results"] as? [[String:Any]] {

You have to iterate over the array to get the values for key overview

      for result in results {
          print(result["overview"] as? String ?? "no value for key overview") 
      }
}

It's highly recommended to use the Codable protocol and custom structs in Swift 4.

vadian
  • 274,689
  • 30
  • 353
  • 361