user2423476
user2423476

Reputation: 2275

Swift get values from JSON

I'm trying to parse the JSON response below using the following code but can't seem to get it to work, how would I do this? Im trying to get "user_guid" and all the "entity_guid" in images.

SWIFT

        do {
            var entity_guid : Int = 0
            var user_guid : Int = 0
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

            // Parse JSON data
            let jsonP = jsonResult?["result"] as! [AnyObject]
            for jsonL in jsonP {
                user_guid = jsonL["user_guid"] as! Int
                entity_guid = jsonL["entity_guid"] as! Int
            }


        } catch {

        }

JSON

{
 "status":0,
 "result":{
  "user_guid":139219,
  "images":[
   {
    "entity_guid":572356
   },
   {
    "entity_guid":572354
   },
   {
    "entity_guid":572352
   }
]
}
}

Upvotes: 1

Views: 13766

Answers (2)

Satyam
Satyam

Reputation: 15894

Try below code:

do {
        var entity_guid : Int = 0
        var user_guid : Int = 0
        let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]

        // Parse JSON data
        let jsonP = jsonResult?["result"] as! [String:Any]
        user_guid = jsonP["user_guid"] as! Int
        let images = jsonP["images"] as! [[String:Int]]
        for jsonL in images {
            entity_guid = jsonL["entity_guid"]!
        }
    } catch {
        print(error.localizedDescription)
    }

Upvotes: 1

Parth Adroja
Parth Adroja

Reputation: 13514

Replace below code and try to check. You must use Swift datatypes wherever possible.

do {
    var entity_guid : Int = 0
    var user_guid : Int = 0
    let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]

     guard let jsonP = jsonResult["result"] as [String: Any] else {
     return
    }
     user_guid = jsonP["user_guid"] as! Int
     if let jsonArr = jsonP["images"] as? [String] {
        for image in jsonArr {
            entity_guid = image["entity_guid"] as! Int
         }
}

Upvotes: 0

Related Questions