如何从NSData对象[duplicate]获取JSON对象数组

时间:2022-09-25 10:19:59

This question already has an answer here:

这个问题已经有了答案:

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:

我使用的是HTTP GET方法,它返回一个JSON对象数组,这些对象存储在NSData中。数组如下所示:

[{"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?

如何提取这些JSON对象并从NSData中迭代它们?

1 个解决方案

#1


64  

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

如果你正在使用iOS 5.0或以上版本,你可以这样做:

Objective-C

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 2.1

斯威夫特2.1

do {
    let jsonArray = try NSJSONSerialization.JSONObjectWithData(myNSData, options:[])
    print("Array: \(jsonArray)")
}
catch {
    print("Error: \(error)")
}

#1


64  

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

如果你正在使用iOS 5.0或以上版本,你可以这样做:

Objective-C

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 2.1

斯威夫特2.1

do {
    let jsonArray = try NSJSONSerialization.JSONObjectWithData(myNSData, options:[])
    print("Array: \(jsonArray)")
}
catch {
    print("Error: \(error)")
}