2012-10-21 55 views
-3

可能重複:
iPhone/iOS JSON parsing tutorial解析JSON數據

我一直在閱讀關於如何分析目標C JSON數據很多教程,但還是我無法弄清楚。我想解析JSON文件中的數據並在屏幕上顯示它。

例如,

我想從here分析數據,並獲得不同的變量不同的零售商的所有值,這樣我可以在以後使用它們。

我該怎麼辦?

+1

採取這個問題看看接受的答案: http://stackoverflow.com/questions/5813077/iphone-ios-json-parsing-tutorial – uldall

+0

看到:HTTP://計算器。 com/questions/10241908/parsing-json-data-in-ios-objective-c-and-displayed-in-tableview-getting-empt – Farshid

+0

尋找更多的例子,如果你無法理解它們,你對目標的理解-C可能不足。 JSON並不複雜! –

回答

2

假設你有一個NSData對象中的數據,你可以使用iOS 5及更高版本中可用的NSJSONSerialization類。

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error 

這是一個類的方法,將您的數據轉換成取決於您的數據對象的內容類似的NSArray,NSDictionary的,NSNumber的對象等。

1

下面介紹如何下載和解析來自Web服務器的數據。請注意,所有這些方法都是同一類的一部分,並且存在類型NSMutableData*_downloadConnection類型NSURLConnection*的實例變量。還要注意這個代碼假定ARC沒有被使用。如果是這樣,只需刪除對象發佈並保留,並確保實例變量是強引用。

-(void)startDownload { 
    NSURL* jsonURL = [NSURL URLWithString:@"http://isbn.net.in/9781449394707.json"]; 

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:jsonURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; 

    _downloadData = [[NSMutableData dataWithCapacity:512] retain]; 

    _downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 

} 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [_downloadData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [_downloadData appendData:data]; 
} 


- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 

    [_downloadConnection release]; 
    _downloadConnection = nil; 

    [_downloadData release]; 
    _downloadData = nil; 
} 


- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSError* jsonError = nil; 

    NSDictionary* jsonDict = nil; // your data will come out as a NSDictionry from the parser 
    jsonDict = [NSJSONSerialization JSONObjectWithData:_downloadData options:NSJSONReadingMutableLeaves error:&jsonError]; 


    if (nil != jsonError) { 
     // do something about the error 

     return; 
    } 

    [_downloadConnection release]; 
    _downloadConnection = nil; 

    [_downloadData release]; 
    _downloadData = nil; 

    // now do whatever you want with your data in the 'jsonDict' 
}