在iPhone应用程序中浏览JSON数据

时间:2010-10-19 09:31:22

标签: iphone objective-c xcode json

我担心我是客观编程的新手,而且我遇到了一个问题,我花了一整天时间想弄清楚,我不能,所以我谦虚地问你们,如果有人可以提供帮助的话。

我正在尝试从在线JSON页面(例如本地服务目录)中读取详细信息并将JSON库安装到Xcode中,它似乎工作正常。我正在为iPhone开发,并安装了所有最新版本。

问题是,我是一个新手还是所有人,我似乎无法从JSON文件中检索出我需要的所有信息。

我正在测试的JSON数据是:

"testlocal_response" =     {
        header =         {
            query =             {
                business = newsagent;
                location = brighton;
                page = 1;
                "per_page" = 1;
                "query_path" = "business/index";
            };
            status = ok;
        };
        records =         (
                        {
                address1 = "749 Rwlqsmuwgj Jcyv";
                address2 = "<null>";
                "average_rating" = 0;
                "business_id" = 4361366;
                "business_keywords" = "<null>";
                "business_name" = "Gloucester Newsagents";
                "data_provider_id" = "<null>";
                "display_details" = "<null>";
                "distance_in_miles" = "0.08";
                fax = "<null>";
                gridx = "169026.3";
                gridy = "643455.7";
                "image_url" = "<null>";
                latitude = "50.82718";
                "logo_path" = Deprecated;
                longitude = "-0.13963";
                phone = 97204438976;
                postcode = "IY1 6CC";
                "reviews_count" = 0;
                "short_description" = "<null>";
                "touch_url" = "http://www.test.com/business/list/bid/4361366";
                town = BRIGHTON;
                url = "<null>";
            }
        );
    };
}

现在,在我的代码ViewController.m页面中,在'connectionDidFinishLoading'区域中我添加了:

  NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
 [responseData release];

 // make sure JSON has all been pulled in
        NSLog(@"This is from the JSON page:\n");
 NSLog(responseString);
 NSError *error;
 SBJSON *json = [[SBJSON new] autorelease];

        // using either of these seems to make no difference?
 NSDictionary *touchDirect = [json objectWithString:responseString error:&error];
 //NSArray *touchDirect = [json objectWithString:responseString error:&error];
 [responseString release]; 

 if (touchDirect == nil)
  label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]];
 else {  
  NSMutableString *text = [NSMutableString stringWithString:@"Test directory details:\n"];

  [text appendFormat:@"%@\n", [[[[touchDirect objectForKey:@"testlocal_response"] objectForKey:@"header"] objectForKey:@"query"] objectForKey:@"business"]];

  label.text =  text;

测试这个我获得了返回的业务('newsagent')的值,或者是正确的位置('brighton')。我的问题是,我无法进一步了解JSON。我不知道如何提取实际“记录”的结果,在测试示例中只有一个但可以使用括号'('和')'进行更多划分。

一旦我尝试访问这些记录区域中的数据(例如'address1'或'latitude'或'postcode'),它就会失败并告诉我“无法识别的选择器发送到实例”

请谁能告诉我我做错了什么?!我已经尝试了很多不同的东西,只是无法进一步!我在网上看过各种不同的东西,但似乎没有什么能帮到我。

任何回复都深表感谢。我在iPhone SDK上发布了一个问题,但还没有得到有用的回复。

非常感谢,

-Robsa

2 个答案:

答案 0 :(得分:0)

您是否验证了JSON?

目前尚不清楚您是如何尝试访问您说错误的对象。您遇到问题的具体行将会有所帮助。

为了便于阅读,通常更容易设置指向您要访问的字典的指针。

NSDictionary *records = [[objectForKey:@"testlocal_response"] objectForKey@"records"];

...然后

NSString *businessName = [records objectForKey:@"business_name"];
float latitude = [[records objectForKey:@"latitude"] floatValue];

答案 1 :(得分:0)

好吧,我终于把它整理出来了!我将记录放在NSString中,然后我可以使用objectAtIndex访问它。 这是它的主要Viewcontroller.m代码:

- (void)viewDidLoad {   
    [super viewDidLoad];

    responseData = [[NSMutableData data] retain];       
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"*URL TO JSON DATA HERE*"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];               
    NSMutableArray *touchDirect = [json objectWithString:responseString error:&error]; 
    NSString *touchRecord = [[touchDirect objectForKey:@"touchlocal_response"] objectForKey:@"records"];

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {      
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];
    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];
    //Retrieves the JSON header Data, returning info such as 'status' [which should return 'ok']
    NSMutableArray *touchDirect = [json objectWithString:responseString error:&error]; 
    //Puts the records returned into a string called touchRecord
    NSString *touchRecord = [[touchDirect objectForKey:@"touchlocal_response"] objectForKey:@"records"];
    [responseString release];   

    // test results   
    [text appendFormat:@" Address: %@\n", [[touchRecord objectAtIndex:0] objectForKey:@"address1"]];
    [text appendFormat:@" Phone:   %@\n", [[touchRecord objectAtIndex:0] objectForKey:@"phone"]];
    [text appendFormat:@" Address Data record 2: %@\n", [[touchRecord objectAtIndex:1] objectForKey:@"address1"]];
    [text appendFormat:@" Phone Data record 2:   %@\n", [[touchRecord objectAtIndex:1] objectForKey:@"phone"]];

现在似乎工作正常。我现在还有一个if..else if语句来捕获错误。这段代码看起来好吗?

感谢提示,尼克 - 我只是想在整理代码之前获得正确的输出。我正在使用NSMutableArray将我的JSON放入最初,这样可以吗?将它放入NSDictionary有什么好处?

的问候,

Robsa