shesh nath shesh nath - 4 months ago 4
Swift Question

How to parse JSON Data without third party library in swift 2

I know there are several question available for same question, but none of them is working for me.
My code to convert from NSData to JSON is

var locateData: NSData = NSData(contentsOfURL: location)!

do {

responseObject = try NSJSONSerialization.JSONObjectWithData(locateData, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
let arrayStatuses: NSArray = responseObject["statuses"] as! NSArray
print("Data items count: \(arrayStatuses.count)")

}

catch _ as NSError {

}


print count alway show 1, i need to create model class of dictionary available inside array

here is my sample JSON

{
"statuses": [
{
"created_at": "Wed Jul 27 07:31:26 +0000 2016",
"name" :"shesh"
},
{
"created_at": "Wed Jul 27 07:31:26 +0000 2016",
"name" :"shesh"
},
{
"created_at": "Wed Jul 27 07:31:26 +0000 2016",
"name" :"shesh"
},
{
"created_at": "Wed Jul 27 07:31:26 +0000 2016",
"name" :"shesh"
}]
}

Answer

First of all use always native Swift collection types because the Foundation counterparts lack the important type information.

This code prints all values for the keys text, truncated and created_at

let locateData = NSData(contentsOfURL: location)!

do {
  if let responseObject = try NSJSONSerialization.JSONObjectWithData(locateData, options: []) as? [String:AnyObject],
    arrayStatuses = responseObject["statuses"] as? [[String:AnyObject]] {
    print("Data items count: \(arrayStatuses.count)")
    for status in arrayStatuses {
      let created = status["created_at"] as! String
      let truncated = status["truncated"] as! Bool
      let text = status["text"] as! String
      print("text: \(text), created: \(created), truncated: \(truncated)")
    }
  }

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