Swift 2 Parsing JSON - cannot index value of type "AnyObject"

I tried the following examples for parsing a JSON file (for example, the answer to another question posted here: https://stackoverflow.com/a/16729/ ) but cannot get it working. Now I get the error message "I can’t adjust the value of the type" AnyObject "to" let ... = item ["..."] as the string "String".

func connectionDidFinishLoading(connection: NSURLConnection) { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject> if let searchResults = jsonResult["Search"] as? [AnyObject] { for item in searchResults { let title = item["Title"] as? String //Error Here let type = item["Type"] as? String //Error Here let year = item["Year"] as? String //Error Here print("Title: \(title) Type: \(type) Year: \(year)") } } } catch let error as NSError { NSLog("JSON Error: \(error)") } } 

JSON example:

 { "Search": [ { "Title":"Example 1", "Year":"2001", "Type":"Type1" }, { "Title":"Example 2", "Year":"2006", "Type":"Type1" }, { "Title":"Example 3", "Year":"1955", "Type":"Type1" } ]} 
0
json swift2
Oct 25 '15 at 0:17
source share
2 answers

try it

 func connectionDidFinishLoading(connection: NSURLConnection) { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject> if let searchResults = jsonResult["Search"] as? [[String: AnyObject]] { for item in searchResults { let title = item["Title"] let type = item["Type"] let year = item["Year"] print("Title: \(title) Type: \(type) Year: \(year)") } } } catch let error as NSError { NSLog("JSON Error: \(error)") } } 
+2
25 Oct '15 at 0:24
source share

You can do it

 let title : String if let titleVal = item["Title"] as? String { title = titleVal print(title) } 

This will take care of whether the value of the Title property is null or not. If it is not null, it will read the value and set the variable titleVal .

If you are sure that it will never have a null value, you can use this code

 let title = item["Title"] as! String 
0
Oct 25 '15 at 0:20
source share



All Articles