2011-12-31 23 views
2

我使用的是iOS 5的新功能解析JSON,我不知道這是爲什麼,我沒有得到任何鍵值對。 「aStr」(數據的字符串表示形式)將正確的JSON放在輸出窗口上,但我在「dicData」中什麼都沒有,並且也沒有錯誤。NSJSONSerialization沒有創造鍵值對

任何幫助,非常感謝。

這是我在用

NSError *error = nil; 
    NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:@"http://www.macscandal.com/?json=get_post&post_id=436"]]; 

NSString* aStr; 
aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 

//NSLog(@"data = %@",aStr); 
NSDictionary *dicData = [NSJSONSerialization 
          JSONObjectWithData:data 
          options:NSJSONReadingAllowFragments 
          error:&error]; 
//NSLog(@"error = %@",error); 
NSString *title = [dicData objectForKey:@"title"]; 

回答

1

你JSON的格式是這樣的:

{ 
    "status": "ok", 
    "post": { 
    "id": 436, 
    "type": "post", 
    "slug": "foxconn-likely-to-get-assembly-contract-for-apple-tv-set", 
    "url": "http:\/\/www.macscandal.com\/index.php\/2011\/12\/28\/foxconn-likely-to-get-assembly-contract-for-apple-tv-set\/", 
    "status": "publish", 
    "title": "Foxconn Likely to get Assembly Contract for Apple TV Set", 
... 

我沒有使用過NSJSONSerialization只是遵循自然JSON解析ALG這是我會怎樣嘗試獲取它。

NSDictionary *dicData = [NSJSONSerialization 
          JSONObjectWithData:data 
          options:NSJSONReadingAllowFragments 
          error:&error]; 

NSDictionary *postData = [dicData objectForKey:@"post"]; 
NSString *title = [postData objectForKey:@"title"]; 

編輯

只是一個簡單的檢查方法:

-(void)check{ 

    NSError *error = nil; 
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.macscandal.com/?json=get_post&post_id=436"]]; 

    NSDictionary *dicData = [NSJSONSerialization 
          JSONObjectWithData:data 
          options:NSJSONReadingAllowFragments 
          error:&error]; 

    NSDictionary *postData = [dicData objectForKey:@"post"]; 
    NSString *title = [postData objectForKey:@"title"]; 

    NSLog(@"%@", title); 
} 
+0

感謝您的回答,但塞浦路斯我仍然得到0鍵/值對?任何想法? – Leo 2011-12-31 18:57:43

+0

不知道爲什麼這樣。我會嘗試檢查它。 – Cyprian 2011-12-31 19:40:34

+0

我只是想它和它的工作對我來說:'2011-12-31 20:42:04.595的UIView演示[2406:F803]富士康可能會得到議會合同蘋果電視Set' – Cyprian 2011-12-31 19:42:50