如何解析iOS應用中的JSON字符串?使用SBJSON。運行下面的代碼。獲取數據是成功的,但即使JSON字符串包含條目,數組中條目數的計數也爲零。我的問題是如何查詢循環中的JSON字符串?iOS:JSON字符串NSArray不按預期工作
謝謝!
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://safe2pee.org/api/proxlist.php?location=37.7626214,-122.4351661&distance=1"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"string equal = %@", json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON b objects
NSArray *bathrooms = [parser objectWithString:json_string error:nil];
NSLog(@"count = %d", [bathrooms count]);
// Each element in bathrooms is a single bathroom
// represented as a NSDictionary
for (NSDictionary *bathroom in bathrooms)
{
// You can retrieve individual values using objectForKey on the bathroom NSDictionary
// This will print the tweet and username to the console
NSLog(@"%@ - %@", [bathroom objectForKey:@"name"], [[bathroom objectForKey:@"lat"] objectForKey:@"long"]);
}
嘗試'[json_string JSONValue]''。 –