2011-10-21 32 views
0

如何解析iOS應用中的JSON字符串?使用SBJSON。運行下面的代碼。獲取數據是成功的,但即使JSON字符串包含條目,數組中條目數的計數也爲零。我的問題是如何查詢循環中的JSON字符串?iOS:JSON字符串NSArray不按預期工作

謝謝!

// Create new SBJSON parser object 
SBJsonParser *parser = [[SBJsonParser alloc] init]; 

// Prepare URL request to download statuses from Twitter 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://safe2pee.org/api/proxlist.php?location=37.7626214,-122.4351661&distance=1"]]; 

// Perform request and get JSON back as a NSData object 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

// Get JSON as a NSString from NSData response 
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 

NSLog(@"string equal = %@", json_string); 

// parse the JSON response into an object 
// Here we're using NSArray since we're parsing an array of JSON b objects 
NSArray *bathrooms = [parser objectWithString:json_string error:nil]; 

NSLog(@"count = %d", [bathrooms count]); 

// Each element in bathrooms is a single bathroom 
// represented as a NSDictionary 
for (NSDictionary *bathroom in bathrooms) 
{ 
    // You can retrieve individual values using objectForKey on the bathroom NSDictionary 
    // This will print the tweet and username to the console 
    NSLog(@"%@ - %@", [bathroom objectForKey:@"name"], [[bathroom objectForKey:@"lat"] objectForKey:@"long"]); 
} 
+0

嘗試'[json_string JSONValue]''。 –

回答

2

這是因爲它不起作用。這不是有效的JSON字符串。這是2個JSON字典,背靠背,中間以逗號分隔。它錯過了包裝[]。如果你真的測試了-objectWithString:error:的結果值,你會發現它是零,如果你在NSError**中傳遞error參數,你會得到一個錯誤消息,告訴你它是無效的JSON。

+0

對不起,我應該澄清我沒有發佈整個json字符串。我要編輯出來。整個字符串相當大。 – user1003426

+0

我的觀點依然存在;很可能你會得到'無'。你需要傳入一個錯誤變量,測試'-objectWithString:error:'的結果,如果它是'nil'則打印出錯誤。 –

+0

這是錯誤,回來.... 2011-10-20 17:35:22.868 JSOHHelp [8887:f803]錯誤是錯誤域= org.brautaset.SBJsonParser.ErrorDomain代碼= 0「意外的輸入結束」 UserInfo = 0x68831d0 {NSLocalizedDescription =意外的輸入結束} – user1003426

0

我查看了在您的帖子中請求URL時返回的JSON字符串,並且它看起來好像被服務器錯誤地截斷了。返回的JSON字符串包含一個字典結構,其中包含一個名爲「bathrooms」的鍵,其值是一個字典結構數組。這些浴室字典結構中的每一個都包含「投標」,「名稱」,「拉特」,...,「方向」和「評論」等幾個字段。

當我滾動到收到的JSON的結尾時,我看到「浴室」陣列下的完整字典結構(「bid」是「MTIyIFMyUA ==」,「name」是「Momi Tobi's」。結構包含它的右大括號,但數組的結尾「]」缺失,並且頂級字典結構的結尾「}」缺失。

您應該看看服務,看看它爲什麼返回無效的JSON一旦你有一個有效的字符串,看起來你應該從一個NSDictionary開始,並解析它是這樣的:

NSDictionary *result = [parser objectWithString:json_string error:nil]; 
NSArray *bathrooms = [result objectForKey:@"bathrooms"];