yagiz yagiz - 5 months ago 12
JSON Question

Parsing JSON from NSData with Swift

I want to parse data in array but I can't. Please let me know if you have any suggestion. Here is my data sample:

[{"ListSequence":1,"StarTime":"15.06.2016 09:00","WorkTime":15,"EndTime":"15.06.2016 09:15","Appointment":"","CustomerId":"12345","Name":"","Address":"bla bla"}, {"ListSequence":2,"StarTime":"15.06.2016 09:20","WorkTime":15,"EndTime":"15.06.2016 09:35","Appointment":"","CustomerId":"54321","Name":"","Address":"bla bla"}]


This is my function:

func parserJSON(data: NSData){
var names = [String]()
do {
if let ipString = NSString(data:data, encoding: NSUTF8StringEncoding) {
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

if let sequences = jsonDictionary["ListSequence"] as? [[String: AnyObject]] {
for sequence in sequences {
if let name = jsonDictionary["Name"] as? String{
names.append(name)
}
}
}
}
} catch {
///alert
}
}

Answer

Your JSON represents an array, not an object. Try this:

func parserJSON(data: NSData){
    var names = [String]()
    do {
        if let ipString = NSString(data:data, encoding: NSUTF8StringEncoding) {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as! [AnyObject]
            names = json.map { ($0 as! [String: AnyObject])["Name"] as! String }
        }
    } catch {
        ///alert
        print(error)
    }
}

NSJSONSerialization is really verbose. Everything is an atomic value (i.e. String), an array ([AnyObject]) or a dictionary ([String: AnyObject]). if you want to convert, you have to do it one step at a time.

Comments