ios 如何从 NSData 对象获取一组 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15402416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:43:04  来源:igfitidea点击:

How to get an array of JSON objects from NSData object

iosobjective-cjsonswiftnsdata

提问by Julian Coltea

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 中遍历它们?

回答by Simon Germain

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

如果您使用的是 iOS 5.0 及更高版本,则可以执行以下操作:

Objective-C:

目标-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)")
}