0

Here's the usual JSON I see:

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

But I am trying to parse this format of JSON, without the object ("employees" from the example above):

[{"id":"1","company":"1","facility":"2","starttime":"1454936400","complete_time":"1454979600","scheduled_hours":"12"},{"id":"3","company":"1","facility":"2","starttime":"1455021660","complete_time":"1455061660","scheduled_hours":"12"}]

Here's the code that I'm trying to use:

 let requestURL: NSURL = NSURL(string: url)!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                    if let stations = json[1] as? [[String: AnyObject]] {
                        print(json)
                        for station in stations {

                            if let name = station["company"] as? String {
                               print(name)

                            }
                        }

                    }

                }catch {
                    print("Error with Json: \(error)")

                }

            }

        }

        task.resume()

But I am not able to output any of the values from JSON data. How do I do it? I am very new in Swift and XCode.

Or if I can format my data to look like the first JSON, would it be alright? The data is being returned as an array from an SQL query.

UPDATE: When I print(json[1]) it only prints the second set. I think I'm getting closer.

3
  • It isn't clear what you mean. Are you saying that you want to be able to handle JSON input that does not have an outer dictionary, but instead just has an array of items? Your second JSON example looks to be an array of dictionaries with completely different keys. Commented Feb 29, 2016 at 17:10
  • I mean, how do I parse it without the outer dictionary just like "employees" from the first example. Commented Mar 1, 2016 at 12:20
  • There is a popular library called SwiftyJSON. You may want to have a look at it. Commented Mar 1, 2016 at 13:02

2 Answers 2

1

NSJSONSerialization.JSONObjectWithData can be tricky because it can return either an Array aka [AnyObject] or a Dictionary aka [String: AnyObject].

Then you have to test what the result is :

let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let json = jsonData as? [[String: AnyObject]] {
    // json starts with an array
    for value in json {
        // loop through array
    }
} else if let json = jsonData as? [String: AnyObject] {
    // json starts with a key
    for (key, value) in json {
       // loop through dictionary key/values
    }
} else {
    // This json is broken
}
Sign up to request clarification or add additional context in comments.

8 Comments

It always go to the Else clause. But if I print the json variable, I can see my data intact.
I updated my answer with a fix json is [AnyObject] instead of json is [String], does it solve your problem ?
JSON starts with an array. So how do I loop and get the values?
I added the different loops you need in both cases ;)
I get "Type AnyObject does not conform to protocol SequenceType in the for loop line
|
0

1-check that statusCode condition is true(200 or "200"?)

2-print data before try catch

if (statusCode == 200) {
    print(data)
            do{
               ......
              }

3- print json object

do{

  let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
  print(json)

and

4-check json[1] same as [[String: AnyObject]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.