2012-09-16 75 views
1

我正在向URL請求一個API,但我不知道如何呈現JSON,它生成一個像這樣的多個用戶的數組[{"user": "value"}, {"user":"value"}],我試圖使用TableView,所以我需要一個NSDictionary,但我認爲更好地呈現像{users: [{"user": "value"}, {"user":"value"}]}的JSON。我有這樣的代碼,以使該請求JSON到Objective-C字典

#import "JSONKit.h" 
NSError *error = nil; 
NSURLResponse *response = nil; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost:3000/getusers"]]; 
[request setHTTPMethod:@"GET"]; 
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
users = [[jsonData objectFromJSONData] objectForKey:@"users"]; 
usersKeys = [users allKeys]; 

,但我發現這個錯誤

2012-09-16 18:51:11.360的tableview [2979:C07] - [JKArray allKeys]:無法識別的選擇發送到實例0x6d30180 2012-09-16 18:51:11.362 tableview [2979:c07] *由於未捕獲的異常'NSInvalidArgumentException'而終止應用,原因:' - [JKArray allKeys]:無法識別的選擇器發送到實例0x6d30180'

我真的不知道如何做到這一點,所以任何幫助都很有用,謝謝

回答

2

您正在收到該錯誤,因爲無論從「jsonData」中解析出來的結果都不一定是您所期望的(即,一本字典)。

也許你需要在你的代碼中進行一些錯誤檢查。

例如:

NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
if(jsonData) 
{ 
    id objectReturnedFromJSON = [jsonData objectFromJSONData]; 
    if(objectReturnedFromJSON) 
    { 
     if([objectReturnedFromJSON isKindOfClass:[NSDictonary class]]) 
     { 
      NSDictionary * dictionaryFromJSON = (NSDictionary *)objectReturnedFromJSON; 
      // assuming you declared "users" & "usersKeys" in your interface, 
      // or somewhere else in this method 
      users = [dictionaryFromJSON objectForKey:@"users"]; 
      if(users) 
      { 
       usersKeys = [users allKeys]; 
      } else { 
       NSLog(@"no users in the json data"); 
      } 
     } else { 
      NSLog(@"no dictionary from the data returned by the server... check the data to see if it's valid JSON"); 
     } 
    } else { 
     NSLog(@"nothing valid returned from the server..."); 
    } 
} else { 
    NSLog(@"no data back from the server"); 
} 
0

我想在這樣的

NSError *error = nil; 
NSURLResponse *response = nil; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost:3000/getusers"]]; 
[request setHTTPMethod:@"GET"]; 
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

JSONDecoder *decoder = [[JSONDecoder alloc] 
         initWithParseOptions:JKParseOptionNone]; 
NSArray *json = [decoder objectWithData:jsonData]; 

NSMutableArray *objects = [[NSMutableArray alloc] init]; 
NSMutableArray *keys = [[NSMutableArray alloc] init]; 
for (NSDictionary *user in json) { 
    [objects addObject:[user objectForKey:@"user" ]]; 
    [keys addObject:[user objectForKey:@"value" ]]; 
} 
users = [[NSDictionary alloc] initWithObjects:objects forKeys:keys]; 
NSLog(@"users: %@", users); 
usersKeys = [users allKeys]; 

但它不尋找有效的許多項目或我錯了?