19

So I'm using an HTTP GET method which returns an array of JSON objects, which are stored in NSData. The array looks like this:

[{"created_at":"2013-03-09T04:55:21Z","data_type":"image","id":5354,"latitude":37.785834,"longitude":-122.406417,"name":"tempObject","privacy":"public","radius":1000.0,"updated_at":"2013-03-09T04:55:21Z","user_id":101},{"created_at":"2013-03-10T20:57:08Z","data_type":"image","id":5364,"latitude":37.785834,"longitude":-122.406417,"name":"tempObject","privacy":"public","radius":1000.0,"updated_at":"2013-03-10T20:57:08Z","user_id":101}]

How would I go about extracting these JSON objects and iterate through them from the NSData?

Simon Germain
  • 6,834
  • 1
  • 27
  • 42
Julian Coltea
  • 3,599
  • 10
  • 26
  • 32
  • Did you try searching "ios json nsdata"? It seems to turn up any number of already-answered questions on that exact topic... – Bill Patterson Mar 14 '13 at 06:15
  • 1
    http://stackoverflow.com/questions/15180036/putting-json-into-an-array/15181743#15181743 – LE SANG Mar 14 '13 at 06:15
  • The "This question already has an answer here" did not give me the adequate answer. I need some practical answer like the answer on this page. This question is not a duplicate from the one on the top. – Chen Li Yong Jun 08 '16 at 02:12

1 Answers1

77

If you're using iOS 5.0 and up, you can do this:

Objective-C:

NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error];

if (error != nil) {
    NSLog(@"Error parsing JSON.");
}
else {
    NSLog(@"Array: %@", jsonArray);
}

Swift:

do {
    let jsonArray = try JSONSerialization.jsonObject(with: myNSData, options:[])
    print("Array: \(jsonArray)")
}
catch {
    print("Error: \(error)")
}
Yash Jadhav
  • 95
  • 1
  • 14
Simon Germain
  • 6,834
  • 1
  • 27
  • 42