如何在Objective-C中迭代一个简单的JSON对象?

use*_*605 3 json objective-c nsjsonserialization

我是Objective-C的新手,我是一名核心的Java和Python老手.

我创建了一个Objective-C脚本来调用URL并获取URL返回的JSON对象:

// Prepare the link that is going to be used on the GET request
NSURL * url = [[NSURL alloc] initWithString:@"http://domfa.de/google_nice/-122x1561692/37x4451198/"];

// Prepare the request object
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                            cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                        timeoutInterval:30];

// Prepare the variables for the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;

// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];

// Construct a Array around the Data from the response
NSArray* object = [NSJSONSerialization
                   JSONObjectWithData:urlData
                   options:0
                   error:&error];


//NSLog(object);
// Iterate through the object and print desired results
Run Code Online (Sandbox Code Playgroud)

我到目前为止:

NSString* myString = [@([object count]) stringValue];

NSLog(myString);
Run Code Online (Sandbox Code Playgroud)

这返回了这个数组的大小,但是我如何遍历这个JSON对象并打印每个元素?

这是我正在加载的JSON:

{
    "country": "United States",
    "sublocality_level_1": "",
    "neighborhood": "University South",
    "administrative_area_level_2": "Santa Clara County", 
    "administrative_area_level_1": "California",
    "locality": "City of Palo Alto",
    "administrative_area_level_3": "",
    "sublocality_level_2": "",
    "sublocality_level_3": "",
    "sublocality":""
}
Run Code Online (Sandbox Code Playgroud)

Zev*_*erg 9

JSON对象的顶级对象是字典,而不是数组,如花括号所示.如果您不确定是否要获取数组或字典,可以执行以下安全检查:

// Construct a collection object around the Data from the response
id collection = [NSJSONSerialization JSONObjectWithData:urlData
                                                options:0
                                                  error:&error];

if ( collection ) {
    if ( [collection isKindOfClass:[NSDictionary class]] ) {
        // do dictionary things
        for ( NSString *key in [collection allKeys] ) {
            NSLog(@"%@: %@", key, collection[key]);
        }
    }
    else if ( [collection isKindOfClass:[NSArray class]] ) {
        // do array things
        for ( id object in collection ) {
            NSLog(@"%@", object);
        }
    }
}
else {
    NSLog(@"Error serializing JSON: %@", error);
}
Run Code Online (Sandbox Code Playgroud)