2013-02-18 78 views
0

我想解析我的JSON到一個NSDictionary。以下是我用於解析的方法。json是不正確解析objective-c

+ (NSDictionary *)executeGenkFetch:(NSString *)query 
{ 
    query = [NSString stringWithFormat:@"%@", query]; 
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query); 
    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding]; 
    NSError *error = nil; 
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil; 
    if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription); 
    NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results); 
    return results; 
} 

這裏是我如何使用這個功能。

+(NSArray *)getCommentsWithParam:(NSString *)Param 
{ 
    NSString *request = [NSString stringWithFormat:@"https://graph.facebook.com/comments/?ids=%@",Param]; 
    NSLog(@"request is %@",request); 
    NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param]; 
    return [[self executeGenkFetch:request] valueForKey:vfk]; 
} 

問題是當我記錄從getCommentsWithParam返回的NSArray時,我總是得到NULL。但是當我看到從日誌

NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results); 

我得到我想要的JSON。對出現問題的任何幫助?

回答

5

這是很難不看到實際的JSON數據說,但可能在

NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param]; 
return [[self executeGenkFetch:request] valueForKey:vfk]; 

你必須使用valueForKeyPath代替valueForKey,因爲vfk關鍵路徑有幾個關鍵組件(分立點)。

更新:另一個問題是頂級的關鍵Param是一個HTTP URL,幷包含點。但是在鍵值編碼中,點用於分隔關鍵組件。因此,您不能使用Param作爲關鍵組件。使用objectForKey代替頂級密鑰:

NSDictionary *results = [self executeGenkFetch:request]; 
return [[results objectForKey:Param] valueForKeyPath:@"comments.data"]; 
+0

Martin R,如果您想查看JSON數據,請點擊此處。 https://graph.facebook.com/comments/?ids=http://www.krcgenk.be//nl/nieuws/show/barda-en-vossen-twijfelachtig-voor-kv-kortrijk/1330 – Steaphann 2013-02-18 10:58:19

+0

ValueForKeyPath是也沒有工作。但是,當我將NSDictionary結果記錄在executeGenkFetch中時。我得到正確的字典 – Steaphann 2013-02-18 10:59:04

+0

嘗試像NSDictionary * result = [[[self executeGenkFetch:request] objectForKey:@「comments」] objectForKey:@「data」];然後對於(結果NSDictionary *詞典){/ /做一些評論信息} – 2013-02-18 11:02:11