-1

I have this code for download data:

let parameters = [
            "NationalCode": "06090632",
            "password": "0012"
        ]
let url = "http://android/home/login"
 Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseJSON { response in

            if let data = response.data {
                let json = String(data: data, encoding: String.Encoding.nonLossyASCII)
                print(json)
                self.lbl1.text=json

                }
            }

I have this result that is true:

Optional("{\"id\":\"3\",\"name\":\"jac\"}")

Now I want to loop each item of result. I want to print "id" in one label and "name" in another label. How can I do this? (I am new in Swift)

Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
user3805066
  • 13
  • 1
  • 5
  • 2
    please correctly format your code. – Raghav Garg Sep 02 '17 at 14:31
  • New in swift 4: Can use JSONDecoder. Implement the Codable protocol in your model. Example: class Model: Codable { var id: NSNumber? var name: String? } // let decoder = JSONDecoder() let model = try decoder.decode(Model.self, from: data) print("\(model.name)") – panychyk.dima Sep 02 '17 at 17:01

1 Answers1

1

You need to use the JSONSerialization object to correctly parse your json. This object have the static method jsonObject wich return back an Any Object

JSON are represented by Dictionary or Array, so you need to cast the Any returned with the correctly type of your JSON

In your example, the JSON contains a Dictionary. The keys are ever String Type, so you need to decide the Type of value associated on the Key. In your example the Type are all String.

So, you need to do this:

let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = json as? [String:String] else { return }
print(dictionary["name"])

Hope this help you ;)

Giuseppe Sapienza
  • 4,101
  • 22
  • 23