2011-12-30 86 views
5

我有格式化這樣NSJSONSerialization

serveices問題,一些公共服務JSON
jsonFlickrFeed({ 
     "title": "Uploads from everyone", 
     "link": "http://www.flickr.com/photos/", 
     "description": "", 
     "modifi ... }) 

NSJSONSerialization似乎無法使其工作

NSURL *jsonUrl = [NSURL URLWithString:@"http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=yahoo&callback=YAHOO.Finance.SymbolSuggest.ssCallback"]; 
NSError *error = nil; 
NSData *jsonData = [NSData dataWithContentsOfURL:jsonUrl options:kNilOptions error:&error]; 
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error]; 
NSLog(@"%@", jsonResponse); 

回答

5

我認爲NSJSONSerialization無法處理在您的JSON代碼中使用jsonFlickrFeed(...)的。問題是純粹的響應是無效的JSON(測試它here)。

所以你將不得不建立一個解決這個問題的方法。你可以例如搜索字符串jsonFlickrFeed(在響應中,並刪除它或 - 更簡單的方法 - 只是切斷開始,直到有效的JSON啓動並切斷最後一個字符(應該是括號)

3

的Flickr確實與他們的JSON一些不好的事情分析器無法應付:

  • 他們開始與「jsonFlickrFeed(」和結束「)」
    • 這意味着根對象是不有效
  • 他們不正確地轉義單引號..例如。 \'
    • 這是無效的JSON,並會使解析器傷心!

對於那些希望處理弗裏克JSON提要

//get the feed 
NSURL *flickrFeedURL = [NSURL URLWithString:@"http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=data"]; 
NSData *badJSON = [NSData dataWithContentsOfURL:flickrFeedURL]; 
//convert to UTF8 encoded string so that we can manipulate the 'badness' out of Flickr's feed 
NSString *dataAsString = [NSString stringWithUTF8String:[badJSON bytes]]; 
//remove the leading 'jsonFlickrFeed(' and trailing ')' from the response data so we are left with a dictionary root object 
NSString *correctedJSONString = [NSString stringWithString:[dataAsString substringWithRange:NSMakeRange (15, dataAsString.length-15-1)]]; 
//Flickr incorrectly tries to escape single quotes - this is invalid JSON (see http://stackoverflow.com/a/2275428/423565) 
//correct by removing escape slash (note NSString also uses \ as escape character - thus we need to use \\) 
correctedJSONString = [correctedJSONString stringByReplacingOccurrencesOfString:@"\\'" withString:@"'"]; 
//re-encode the now correct string representation of JSON back to a NSData object which can be parsed by NSJSONSerialization 
NSData *correctedData = [correctedJSONString dataUsingEncoding:NSUTF8StringEncoding]; 
NSError *error = nil; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:correctedData options:NSJSONReadingAllowFragments error:&error]; 
if (error) { 
    NSLog(@"this still sucks - and we failed"); 
} else { 
    NSLog(@"we successfully parsed the flickr 'JSON' feed: %@", json); 
} 

道德故事 - Flickr是淘氣 - 咂嘴