2013-04-04 88 views
1

所以我很新的ios开发,我创建我的第一个应用程序连接到服务器,并拉出一些信息。我跟着一些不同的教程,并设法从不同的地方撤回一些JSON。我遇到的问题是我需要拉取的信息没有根元素,我需要更改哪些信息才能将信息提供给我的应用程序?Json没有根元素ios

下面是我使用的代码:

#import "leagueTableViewController.h" 

    #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 

    #define kjsonURL [NSURL URLWithString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] 
    @interface leagueTableViewController() 

     @end 

     @implementation leagueTableViewController{ 

    NSMutableArray *jsonResults; 
    } 

    - (id)initWithStyle:(UITableViewStyle)style 
    { 
    self = [super initWithStyle:style]; 
    if (self) { 
    // Custom initialization 
    } 
     return self; 
     } 

     - (void)viewDidLoad 
     { 
     [super viewDidLoad]; 

     dispatch_async(kBgQueue, ^{ 

      NSData* data = [NSData dataWithContentsOfURL: 

        kjsonURL]; 

      [self performSelectorOnMainThread:@selector(fetchedData:) 

          withObject:data waitUntilDone:YES]; 

      }); 
      } 




     - (void)fetchedData:(NSData *)responseData { 

      NSError* error; 

      NSDictionary* json = [NSJSONSerialization 

         JSONObjectWithData:responseData 

         options:kNilOptions 

         error:&error]; 

     jsonResults = [json objectForKey:@"loans"]; 

     [self.tableView reloadData]; 

     } 


    - (void)didReceiveMemoryWarning 
     { 
     [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
     } 

     #pragma mark - Table view data source 

     - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
     { 

     // Return the number of sections. 
     return 1; 
     } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section 
    { 
    return [jsonResults count]; 
    } 

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 

     { 
     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

     NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row]; 

     NSString *VersionString = [appsdict objectForKey:@"funded_amount"]; 

     NSString *priceString = [appsdict objectForKey:@"loan_amount"]; 


     cell.textLabel.text = [appsdict objectForKey:@"name"]; 

     cell.detailTextLabel.text = [NSString stringWithFormat:@"Version: %@ Price: $ %@ USD",VersionString,priceString]; 



    return cell; 


    } 

     #pragma mark - Table view delegate 

     - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    // NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row]; 
    //  
    // NSString *appURL = [appsdict objectForKey:@"trackViewUrl"]; 
    //  
    // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]]; 
    } 

    @end 

这是上面的代码使用JSON的一个例子,如可以看到根元素:

 { 
     "paging": { 
     "page": 1, 
     "total": 873, 
     "page_size": 20, 
     "pages": 44 
     }, 
     "loans": [{ 
     "id": 544449, 
     "name": "Sajad", 
     "description": { 
      "languages": ["en"] 
      }, 
      "status": "fundraising", 
      "funded_amount": 0, 
      "basket_amount": 0, 
      "image": { 
      "id": 1325179, 
      "template_id": 1 
      }, 
      "activity": "Cloth & Dressmaking Supplies", 
      "sector": "Retail", 
      "use": "to renovate his shop and increase his textile inventory", 
      "location": { 
      "country_code": "IQ", 
      "country": "Iraq", 
      "geo": { 
       "level": "country", 
       "pairs": "33 44", 
       "type": "point" 
      } 
      }, 
      "partner_id": 166, 
      "posted_date": "2013-04-04T15:40:01Z", 
      "planned_expiration_date": "2013-05-04T15:40:01Z", 
      "loan_amount": 2400, 
      "borrower_count": 1 
      } 

这是在JSON我需要得到,但它没有根元素,什么我需要做我的应用程序来显示这一点:

 [{ 
    "position": 1, 
    "team_id": 10260, 
    "team": "Manchester United", 
    "teamshort": "Man Utd", 
    "played": 30, 
    "won": 25, 
    "drawn": 2, 
    "lost": 3, 
    "for": 70, 
    "against": 31, 
    "difference": 39, 
    "home": { 
     "played": 15, 
     "won": 14, 
     "drawn": 0, 
     "lost": 1, 
     "for": 39, 
     "against": 15, 
     "difference": 24 
    }, 
    "away": { 
     "played": 15, 
     "won": 11, 
     "drawn": 2, 
     "lost": 2, 
     "for": 31, 
     "against": 16, 
     "difference": 15 
    }, 
    "points": 77, 
    "info": "championsleague" 
} 
+0

所以,你正在检索的JSON返回一个NSJSONSerialization调用错误? – daltonclaybrook 2013-04-04 15:54:16

+0

这些是**两个完全不同的**响应...顺便说一句... – holex 2013-04-04 15:59:45

+0

第一套json完美工作,但第二套返回错误 __NSCFArray objectForKey: – paulpwr 2013-04-04 16:05:09

回答

1

使用JSON,您需要事先知道结构。向您发送数据的API会让您知道这一点。

您收到错误的原因是因为您正在像NSDictionary一样处理NSArray。这是一个例子。

这应该被解析到的NSArray:

[{ 
    username: 'johndoe' 
}] 

这将是NSDictioanry:

{ 
    username: 'johndoe' 
} 

你的数据是类似于我提出的第一种情况。所以要获取数据,你需要这样的东西:

NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

[[json objectAtIndex: 0] objectForKey:@"thekey"] 
0

第二块

NSData *strippedData = [data subdataWithRange:NSMakeRange(1, data.length-1)]; 

至于您收到错误来讲,这不是一个NSJSONSerialization错误,它说,返回的对象是:如果你带的第一支架关闭您尝试读取它之前将正确解析NSArray类型(即使您期待NSDictionary类型),并且您试图在其上调用objectForKey:,这不是NSArray的一种方法。你应该分析这个数组,看看它是否包含你需要的信息。这可能看起来像这样:

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; 
jsonResults = [[jsonArray objectAtIndex:0] objectForKey:@"loans"]; 

祝你好运。

0

“没有根元素”的第二个响应是无效的JSON。这就是为什么它不能被解析。没有根元素的JSON,只有有效的JSON和无效的JSON。你有几个选择:

  1. 正如@daltonclaybrook建议,去掉领先的“[”。或者,在结尾添加一个额外的“]”。任何更改都会导致有效的JSON。我不喜欢这种方法,因为如果服务器给你打破了JSON,那么它可能不会被一直打破,或者他们可能会在某个时候修复它。

  2. 修复服务器端的JSON。如果你有任何连接到服务器,告诉他们他们的JSON已损坏,并让他们修复它。如果你无法修复,我的吊,,因为处理搞砸的服务器根本就没有乐趣。如果有任何可能解决混乱,这样做而不是试图弄清楚它是如何打破这次并修复它在你的结束。