Vlad Alexeev
Vlad Alexeev

Reputation: 2204

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
}

Upvotes: 1

Views: 460

Answers (3)

Chandan
Chandan

Reputation: 757

Try this code

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

         for dict in response{

             if let first_name = dict["first_name"] as? String {
                 NSLog("first_name = \(first_name)")
             }
         }                      

      }
      else{
           NSLog("not an []")
     }
}

Upvotes: 0

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

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

Upvotes: 3

Özgür Ersil
Özgür Ersil

Reputation: 7013

Problem here is response is an array

if let response = dict["response"] as? NSArray{
   for value in response as? NSDictionary{
      print(value["uid"]) /// prints 111
      print(value["first_name"]) /// prints someName
   }
}

Upvotes: 2

Related Questions