2014-04-16 25 views
-1

我在理解需要從URL中獲取帶mantle.h的JSON文件時遇到了一些麻煩。來自URL的簡單地幔JSON示例

有人可以給我一個它如何工作的例子嗎?

例如: -I有一個網址www.example.com與JSONFile如下:

{ 
    "name": "michael" 
} 

我怎麼能取嗎?

+2

你試過了什麼? – CRDave

回答

4

我使用此過程獲取JSON:

NSURL *s = url;//Put your desird url here 
NSURLRequest *requestURL = [NSURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00]; 
NSHTTPURLResponse *response; 
NSError *error = [[NSError alloc]init]; 
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error]; 
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error]; 

現在dictionaryData包含您的JSON。你可以把它拿來:

NSString *name = [dictionaryData valueForKey:@"name"]; 

並確保你正在異步請求。對於這種把這個代碼塊中:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
    //Put the code here 
}); 

希望這有助於.. :)

+0

非常感謝! – Michael

+0

@mika>不客氣。你應該接受我的答案.. :) – Rashad

0

把它與下面的方法

[super getRequestDataWithURL:urlString 
       andRequestName:sometext]; 

您將得到如果成功

以下方法響應
- (void)successWithRequest:(AFHTTPRequestOperation *)operation withRespose:(id)responseObject withRequestName:(NSString *)requestName { 

NSString *response = operation.responseString; 

id jsonObject = [response objectFromJSONString]; 


if(![super checkforServerRequestFailureErrorMessage:jsonObject]) { 

     [self.leaderboardProxyDelegate leaderboardListSuccessful:jsonObject]; 

} 
} 

您將獲得jsonObject中的字典