Kevin
Kevin

Reputation: 195

Swift3 JSON using Alamofire

I'm new to Alamofire and Swift.

Now, I'm trying to convert JSON from the API, but I don't know how to convert it.

API like this :

[
{    
  "myid": "10303210302003",    
  "mySubid": "10303210302003",    
  "area_pkid": "3"    
},

{      
  "myid": "10303210302004",   
  "mySubid": "10303210302004",    
  "area_pkid": "4"    
}, 
....]

I'm so confused about "[" and "]" , I don't know how to convert it and get myid.

Here is my code

    Alamofire.request(MyURL, method: .get).responseJSON { (response) in

       guard let totalJSON = response.result.value as? [String : Any] else { return } // My code is just return !! WHY??

    }

Upvotes: 0

Views: 123

Answers (2)

Robert F. Dickerson
Robert F. Dickerson

Reputation: 483

Yep, [] is an array and {} represents as Dictionary. So to get myid just do:

   guard let totalJSON = response.result.value as? [Any] else { return }
   if let i = a["myID"] as? String, let a = totalJSON[0] as? [String: Any] 
   {
      print(i)
   }

Upvotes: 1

vadian
vadian

Reputation: 285280

It's simply

guard let totalJSON = response.result.value as? [[String : Any]] else { return }
for item in totalJSON {
   print(item["myid"] as? String ?? "n/a")
}

since the enclosing object is an array ([])

You can even cast the array to [[String:String]] if all values are String

Upvotes: 3

Related Questions