【问题标题】:Moving through JSON data in iPhone app在 iPhone 应用程序中移动 JSON 数据
【发布时间】:2023-03-06 01:16:01
【问题描述】:

恐怕我是 Objective-c 编程的新手,我遇到了一个问题,我花了一整天的时间试图弄清楚但我无法解决,所以我谦虚地问你们是否有人可以提供帮助。

我正在尝试从在线 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。我不知道如何提取实际“记录”的结果,在测试示例中只有一个,但可以使用括号“(”和“)”进行更多划分。

一旦我尝试访问这些记录区域中的数据(例如“地址 1”或“纬度”或“邮政编码”),它就会失败并告诉我“无法识别的选择器已发送到实例”

请谁能告诉我我做错了什么?!我已经尝试了很多不同的东西,但不能再进一步了!我在网上阅读了各种不同的东西,但似乎没有任何帮助。

非常感谢任何回复。我也在 iPhone SDK 上发布了一个问题,但还没有有用的回复。

非常感谢,

-罗布萨

【问题讨论】:

    标签: iphone objective-c xcode json


    【解决方案1】:

    您是否验证了您的 JSON?

    尚不清楚您是如何尝试访问您所说的出错的对象。您遇到问题的特定线路会有所帮助。

    通常更容易设置指向您将要访问的字典的指针以提高可读性..

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

    那么……

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

    【讨论】:

      【解决方案2】:

      嗯,我终于解决了!我将记录放在一个 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 有什么好处?

      问候,

      罗布萨

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-26
        • 2011-02-21
        • 2013-03-06
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        相关资源
        最近更新 更多