简体   繁体   中英

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??

    }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM