ziplodof.S ziplodof.S - 1 month ago 23
JSON Question

apple change my JSON format after using URLSession.shared.dataTask

I am green to swift 3. In order to transfer data between mysql server and iOS, i try to connect my server and device by

URLSession.Shared.dataTask
.
but the format was changed.

from (the format showed in web)

[{"id":"1","names":"abc","pws_1":"password","pws_2":"pw"}]


to (the format show in Xcode)

Optional(<__NSSingleObjectArrayI 0x6200000039e0>(
{
names = abc;
id = 1;
"pws_1" = password;
"pws_2" = pw;
}
)
)


How can I receive data from this "JSONarray"?

P.S.
this is my code:

let url = URL(string: "http://")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in

if error != nil {
print(error)
} else {
do {

let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if json != nil{
if let Jtwo = json as? [String: Any] {
if let names = Jtwo["names"] as? String {
print(names)
}else{
print(Jtwo)
}
}else{
print(json)
}
}else{
print("json nil")
}




//self.statusL.text = names

} catch let error as NSError {
print(error)
}
}

}).resume()

Answer

You can parse and access your JSON Array like this.

URLSession.shared.dataTask(with: request) {data, response, error in
    if error == nil {
        do {

            let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
            if let user = jsonObj.first {
                print(user["names"])
                print(user["id"])
                print(user["pws_1"])
                print(user["pws_2"])
                DispatchQueue.main.async {
                     self.label.text = user["names"]
                }

            }
        }
        catch {  
            print(error)
        }
    }
}.resume()