在某個文本中搜索twitter的iPhone應用程序中的功能。代碼非常簡單,我將url字符串傳遞給twitter api,然後解析結果。儘管JSON解析器的一半時間失敗,並且未轉義的控制字符'0x0'出現錯誤。下面的代碼和完整的錯誤信息。非轉義控制字符的間歇性JSON解析器失敗
- (void)grabData:(NSString *)searchTerm {
NSString *urlString = [NSString stringWithFormat:@"http://search.twitter.com/search.json?q=%@&rpp=25",searchTerm];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"Created url:%@",url);
//Setup and start async download
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(@"Did receive some data %@",jsonString);
//Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
// Build an Array from the dictionary for easy access to each entry
NSDictionary *tweets = [results objectForKey:@"results"];
// Loop through each entry in the dictionary
for(NSDictionary *tweet in tweets) {
// Get the user string for the tweet
NSString *tUser = [tweet objectForKey:@"from_user"];
NSLog(@"Tweet from %@",tUser);
}
}
錯誤來自控制檯的信息,50%的時間,其他50%的信息按預期工作。
2010-12-20 21:22:02.022 TwitterSearch[47362:207] Created url:http://search.twitter.com/search.json?q=red&rpp=25
2010-12-20 21:22:02.361 TwitterSearch[47362:207] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \"Unescaped control character '0x0'\" UserInfo=0x4d6a130 {NSLocalizedDescription=Unescaped control character '0x0'}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: profile_image_url\" UserInfo=0x4d6a200 {NSUnderlyingError=0x4d6a170 \"Unescaped control character '0x0'\", NSLocalizedDescription=Object value expected for key: profile_image_url}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Expected value while parsing array\" UserInfo=0x4d6a240 {NSUnderlyingError=0x4d6a1e0 \"Object value expected for key: profile_image_url\", NSLocalizedDescription=Expected value while parsing array}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: results\" UserInfo=0x4d6a310 {NSUnderlyingError=0x4d6a2d0 \"Expected value while parsing array\", NSLocalizedDescription=Object value expected for key: results}"
)
當它失敗時,JSON的外觀如何? – 2010-12-21 02:40:43