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

时间:2022-09-11 15:26:08

I'm very new to Objective-C, I'm a hardcore Java and Python veteran.

我对Objective-C非常陌生,我是Java和Python的老手。

I've created an Objective-C script that calls a URL and gets the JSON object returned by the URL:

我创建了一个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

I've gotten this far:

我已经这么远:

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

NSLog(myString);

Which returns the size of this array, but how can I loop through this JSON object and print each element?

返回该数组的大小,但是如何循环这个JSON对象并打印每个元素?

Here's the JSON I'm loading:

这是我正在加载的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":""
}

2 个解决方案

#1


8  

The top-level object your JSON object is a dictionary, not an array, as indicated by the curly braces. If you are not sure whether you are going to get an array or a dictionary back, you can do some safety checking like this:

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);
}

#2


1  

Well for starters, the JSON you linked to is not an array, it is a dictionary.

首先,你链接的JSON不是一个数组,它是一个字典。

NSDictionary* object = [NSJSONSerialization
                   JSONObjectWithData:urlData
                   options:0
                   error:&error];

There are a number of ways to iterate through all of the keys/values, and here is one:

有很多方法可以遍历所有的键/值,这里有一个:

for(NSString *key in [object allKeys])
{
   NSString *value = object[key]; // assuming the value is indeed a string
}

#1


8  

The top-level object your JSON object is a dictionary, not an array, as indicated by the curly braces. If you are not sure whether you are going to get an array or a dictionary back, you can do some safety checking like this:

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);
}

#2


1  

Well for starters, the JSON you linked to is not an array, it is a dictionary.

首先,你链接的JSON不是一个数组,它是一个字典。

NSDictionary* object = [NSJSONSerialization
                   JSONObjectWithData:urlData
                   options:0
                   error:&error];

There are a number of ways to iterate through all of the keys/values, and here is one:

有很多方法可以遍历所有的键/值,这里有一个:

for(NSString *key in [object allKeys])
{
   NSString *value = object[key]; // assuming the value is indeed a string
}