user2976267 user2976267 - 4 months ago 7
Swift Question

parsing JSON with Swift

I'm coming from android programming to Swift iOS programming and have a hard time parsing a json
here's String I try to parse :

{"response":[{"uid":111,"first_name":"someName","last_name":"someLastName","photo_100":"http:someUrl/face.jpg"}]}


here how I try to parse this :

if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{
// this part is yet doing ok
if let response = dict["response"] as? [String: AnyObject]{
NSLog("let response \(response)")
if let first_name = response["first_name"] as? String {
NSLog("first_name = \(first_name)")
}
}
else {
NSLog("not an []")
}


the Log message gives me "not an []" as it can't make a response object. As far as I understand, I'm doing right as
[String: AnyObject]
is what is in "response" body of my json

Just in case, here's my Utils.convertStringToDictionary method:

public static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
return json
} catch {
NSLog("Something went wrong")
}
}
return nil
}

Answer
Array in swift denotes with []
Dictionary in swift denotes with [:]
your response parameter is array of dictionary ... so it denotes with [[:]]

so just parse it with [[String: AnyObject]]

if let response = dict["response"] as? [[String: AnyObject]]{
     for user in response{
         NSLog("let response \(user)")
         if let first_name = user["first_name"] as? String {
              NSLog("first_name = \(first_name)")
          }
     }
 }