-1

i am new to swift programming, i have spent considerable amount of time figuring out how to parse json response from alamofire server call. My Json response is

{"customer_info":[{"customer_id":"147","response_code":1}]}

and i want to access both variables. My swift code is

  Alamofire.request(
                URL_USER_REGISTER,
                method: .post,
                parameters: parameters,
                encoding: JSONEncoding.default).responseJSON
                {


                    if let json = response.result.value {

                        print (json)

                    }

                    if let result = response.result.value as? [String:Any] {

                       var names = [String]()


                         do {
                            if let data = data,
                                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                                let blogs = json["customer_info"] as? [[String: Any]] {
                                for blog in blogs {
                                    if let name = blog["customer_id"] as? String {
                                        names.append(name)
                                    }
                                }
                            }
                        } catch {
                            print("Error deserializing JSON: \(error)")
                        }

                        print(names)




                    }

                }

please help

Swan
  • 53
  • 9
  • why you have parenthesis in your JSON? It's not correctly formatted – Fangming Jul 11 '17 at 16:38
  • No i have mistakenly placed it, my json output is {"customer_info":[{"customer_id":"147","response_code":1}]} – Swan Jul 11 '17 at 16:53
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – vadian Jul 11 '17 at 17:18

2 Answers2

0

Your code is parsing correctly. Add the following code to your blog loop and get the second variable out

if let response_code = blog["response_code"] as? Int {
    //Do something here
}

So the complete code you are looking for is

let str = "{\"customer_info\":[{\"customer_id\":\"147\",\"response_code\":1}]}"

let data = str.data(using: .utf8)

do {
    if let data = data,
        let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
        let blogs = json["customer_info"] as? [[String: Any]] {
        for blog in blogs {
            if let name = blog["customer_id"] as? String {
                print(name)
            }
            if let response_code = blog["response_code"] as? Int {
                print(response_code)
            }
        }
    }
} catch {
    print("Error deserializing JSON: \(error)")
}
Fangming
  • 24,551
  • 6
  • 100
  • 90
  • i am getting error on this line if let data = data, it says unresolved identifier data – Swan Jul 11 '17 at 18:31
  • ya correct, i realized its incorrect but i have tried alamofire json options didnt work so far.. any clue will really help – Swan Jul 11 '17 at 18:38
  • i have changed the code to this if let jsonDict = response.result.value as? [String:Any], let dataArray = jsonDict["customer_info"] as? [[String:Any]] { let dataArray2 = jsonDict["customer_id"] as? [[String:Any]] print(dataArray2) } after this code compiles and runs but i get nil as output of this print – Swan Jul 11 '17 at 18:51
  • @Swan Try my updated answer. It's running in my code and printing out correctly. You have a top level dictionary with an array as value of customer_info. Inside each element of the array, you are having a dictionary. So you must first parse it as dictionary, then as an array of dictionary and then do the for loop, like my code – Fangming Jul 11 '17 at 19:13
  • i have changed my code to this for alamofire as per one guide if let jsonDict = response.result.value as? [String:Any], let dataArray = jsonDict["customer_info"] as? [[String:Any]] { let nameArray = dataArray.flatMap { $0["customer_id"] as? Int } let nameArray2 = dataArray.flatMap { $0["respose_code"] as? Int } print(dataArray) } and getting output as [["response_code": 1, "customer_id": 155]] – Swan Jul 12 '17 at 10:54
  • i have tried your code but not working instead i have used alamofire specific code and i am getting array values printed but cant not figureout how to access particular element of an nested array..can you please help – Swan Jul 12 '17 at 13:26
  • @Swan In my answer, are you able to print out `name` and `response_code` ? With the specific JSON you provided in this example, you will be seeing 147 and 1 printed out in console – Fangming Jul 12 '17 at 13:33
  • hi your code is working just fine but how do i allocate my json response to your STR variable its giving error on that – Swan Jul 13 '17 at 09:22
  • @Swan Oh gocha! So my code is just replicate the json respond. The json parsing function needs to start with `Data` (i.e. NSData). In Alamofire, I believe that `response.result.value` gives you the data object – Fangming Jul 13 '17 at 10:20
0

i have modified the code and getting result now

if let jsonDict = response.result.value as? [String:Any],

                        let dataArray = jsonDict["customer_info"] as? [[String:Any]]
                        {
                              let nameArray = dataArray.flatMap { $0["customer_id"] as? String }
                             let nameArray2 = dataArray.flatMap { $0["response_code"] as? Int }

                            if(dataArray.count>0)
                            {
                              //store return customer id and response code

                                let customer_id_received = nameArray[0]
                                let response_code_received = nameArray2[0]

                                if(response_code_received==1)
                                {
                                //proceed with storing customer id in global variable

                                    print(nameArray2[0])

                                }
Swan
  • 53
  • 9