1

So I am having trouble with Swift 3. I am sending a get call to my server and I get the data back that I expect. However I can't figure out how to create objects from the jsonArray so I can easily access the data.

This is my func so far:

func getAllRoles(refreshToken: String){
    print("vi kører getAllRoles \(refreshToken)")

    let urlPath = "http://keebintest-pagh.rhcloud.com/api/users/allroles/"
    let url = NSURL(string: urlPath)
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url as! URL)

    request.addValue(refreshToken, forHTTPHeaderField: "refreshToken")
    request.httpMethod = "GET"



    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Task completed \(data) and response is xxxx")

        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString!)")



        //            Her laver vi data om til en dictionary
        //            let s = (try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)) as! String
        //            print("det virkede?")
        //            print(s)

        //            var json: Array<String>!
        //            do {
        //                json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Array
        //            } catch {
        //                print(error)
        //            }
        //
        //            print("her er mit json \(json[0])")






    })
    task.resume()
}

This is what my console log looks like:

Task completed Optional(56 bytes) and response is xxxx
responseString = [{"id":1,"roleName":"Admin"},{"id":2,"roleName":"User"}]
here is my json {
    id = 2;
    roleName = User;
}

So obviously I get my data, and it is in an array which I can access. However I can't figure out how to create jsonObjects from each of those in the array. Could someone help?

Thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Steffen L.
  • 149
  • 2
  • 14
  • Possible duplicate of [Deserialize a JSON array to a Swift array of objects](http://stackoverflow.com/questions/37149588/deserialize-a-json-array-to-a-swift-array-of-objects) – shallowThought Jan 25 '17 at 14:44

2 Answers2

0

I'm not 100% sure I understand what you mean by "create objects from the jsonArray so I can easily access the data", but assuming you just want to get data out of the json and into your model objects, it looks like you are already on the right path. Simply feed the data into the array builder and then parse it...

    if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
       let role = (JSONObject[0]["roleName"] as? [String: Any])?["roleName"] as? String {
        // do something with the role name here
     }

That [0] would be replaced with a loop index, of course. This code is ugly, so I would recommend taking Russel's suggestion, which makes it MUCH cleaner.

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98
0

Your issue is the response is not an array of strings (Array<String>), its an array of Dictionary<String,Any> (Array<Dictionary<String,Any>> or more simply [[String:Any]]). Try the following:

var json: [[String:Any]]!
do {
    json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
} catch {
    print(error)
}

Although I recommend not using "!" and using optionals or defaults instead like:

var json:[[String:Any]] = []
if let data = data, let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {
    json = jsonResponse
}

Now as for the "json object" you want, the closest thing to that in swift is a the Dictionary which is in the json array in my example. So json[0]["id"] would return 1.

Jose Castellanos
  • 528
  • 4
  • 11