2015-04-23 81 views
1
[ 
    { 
     "Id": 52, 
     "Name": "name1", 
     "author": "john" 
    }, 
    { 
     "Id": 53, 
     "Name": "name2", 
     "author": "jacob" 
    }, 
    { 
     "Id": 54, 
     "Name": "name3", 
     "author": "jobin" 
    } 
] 

我用下面的代碼來獲取並沒有主鍵無法擷取的JSON值在IOS沒有鑰匙

SBJsonParser *parser1 = [[SBJsonParser alloc] init]; 
    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:str2]]; 
    // Perform request and get JSON back as a NSData object 
    NSData *response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil]; 
    NSError *error; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:response1 options:kNilOptions error:&error]; 

解析此JSON數組,但我得到了以下異常

data parameter is nil 

這個異常是發生在這段代碼

NSData *response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil]; 

如何迭代id值?

+0

檢查您是否在NSError變量中發現任何錯誤... –

+0

您是否在'jsonArray'中獲得響應? –

+0

有沒有必要'主鍵'來訪問元素?您可以輕鬆訪問元素。 –

回答

0

你給出的是完美的,它爲我工作嘗試檢查你的API 而你沒有使用SBJson也嘗試打印NSLog(「%@」,jsonArray);

1

你有JSON的數組文件在這裏,所以我想:從sendSynchronousRequest

NSArray *jsonArray = ; //your JSON 

for (NSDictionary *dict in jsonArray) { 
    NSInteger number = [dict[@"Id"] intValue]; 
    NSString *name = dict[@"Name"]; 
    NSString *author = dict[@"author"]; 
} 
+0

發生在這一行的異常'NSData * response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];'所以我如何獲取值? – Divya

+0

確保URL正確,您是否執行正確的HTTP請求類型(GET)? – Halpo

+0

我推薦AFNetworking或MKNetworkKit,來簡化這些東西 – Halpo

0

返回值是無效的。所以數據參數爲零是有道理的。

+ (void)sendAsynchronousRequest:(NSURLRequest *)request 
         queue:(NSOperationQueue *)queue 
      completionHandler:(void (^)(NSURLResponse *response, 
             NSData *data, 
             NSError *connectionError))handler 

您期待的數據值在塊中提供。那就是你想要提取NSArray的地方,並且用它做些事情。

在我目前的項目中,我沒有使用synchronousRequest,而是做了類似的事情。也許這對你有幫助。

NSError *error; 
    // Read the given JSON file from the server 
    NSData *filedata = [NSData dataWithContentsOfURL:url options:kNilOptions error:&error]; 

    if (filedata) 
    { 
     // Read the returned NSData from the server to an NSDictionary object 
     // Essentially this is the bookstore in NSDictionary format. 
     NSArray *bookStore = [NSJSONSerialization JSONObjectWithData:filedata options:kNilOptions error:&error]; 

    }