2013-07-25 68 views
0

我實現JSON解析如下:獲取方法JSON解析在IOS

-(void)getallEvent 
{   
    SBJSON *json = [SBJSON new]; 
    json.humanReadable = YES; 
    responseData = [[NSMutableData data] retain]; 

    NSString *service = @"/GetAllVenue"; 

    NSString *str; 
    str = @"Calagary"; 
    NSString *requestString = [NSString stringWithFormat:@"{\"CityName\":\"%@\"}",str]; 

    //NSLog(@"request string:%@",requestString); 

    // NSString *requestString = [NSString stringWithFormat:@"{\"GetAllEventsDetails\":\"%@\"}",service]; 
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; 

    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"]; 
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; 
    NSString *urlLoc = [fileContents objectForKey:@"URL"]; 
    urlLoc = [urlLoc stringByAppendingString:service]; 
    //NSLog(@"URL : %@",urlLoc); 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; 
    [request setHTTPMethod: @"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody: requestData]; 

    // self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; 



    NSError *respError = nil; 
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ]; 

    if (respError) 
    { 
     NSString *msg = [NSString stringWithFormat:@"Connection failed! Error - %@ %@", 
         [respError localizedDescription], 
         [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Check your network connection" message:msg delegate:self cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
     [alertView show]; 
     [alertView release]; 

    } 
    else 
    { 
     NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding]; 

     NSDictionary *results = [[responseString JSONValue] retain]; 
     //NSLog(@" %@",results); 
     NSString *extractUsers = [[results objectForKey:@"d"] retain]; 
     NSDictionary *finalResult = [[extractUsers JSONValue] retain]; 
     NSLog(@"Final Results : %@",finalResult); 
     listOfEvents = [finalResult objectForKey:@"List of Event details of given Venue"]; 

}

使用此代碼,它減慢應用程序。我如何解析json在後臺? * 此方法適用於Post Method嗎? Post &獲取方法與有什麼不同? *

是否有任何其他方式json解析?

+0

[POST和GET有什麼區別?](http://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get) –

回答

1

您正在進行同步通信請求,導致應用程序變慢。您應該提出異步請求以保持您的應用程序響應。 它沒有任何關於解析JSON數據的問題。

2

您正在使用主線程上執行的同步請求,所以如果您需要在後臺使用異步加載。

POST方法: POST方法產生FORM集合,它被作爲一個HTTP請求正文。表單中鍵入的所有值都將存儲在FORM集合中。

GET方法: GET方法通過將信息附加到URL(帶有問號)並將其存儲爲A查詢字符串集合來發送信息。 Querystring集合作爲名稱/值對傳遞給服務器。 URL的長度應小於255個字符。

An HTTP GET is a request from the client to the server, asking for a resource. 

An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server. 

檢查這個答案詳細信息:what-is-the-difference-between-post-and-get

+0

感謝您的回覆.. – user2526811

+0

@Nishant Tyagi你的回答清除了我的懷疑 – ChenSmile

1

我會建議在您的環境中使用AFNetworking這將簡化JSON你得到的連接管理,後臺排隊的執行和解析背部形成服務器。

下面的代碼示例將創建一個HTTP客戶端,其中base URL (<hostname>)並從給定路徑獲得一個JSON負載。網絡要求在後臺運行,並運行一個給定塊完成

httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 

// set the type to JSON 
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
[httpClient setDefaultHeader:@"Accept" value:@"application/json"]; 
[httpClient setParameterEncoding:AFJSONParameterEncoding]; 

// Activate newtork indicator   
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 

// Request the <path> from the server and parse the response to JSON 
// this calls a GET method to <hostname>/<path> 
[httpClient getPath:<your path> parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    // responseObject is a JSON object here 
    // 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    // handle error 
}]; 
0

時得到:隨着get方法的值是通過與URL追加查詢字符串發送。因此,當瀏覽器顯示頁面時,您可以在地址欄上看到名稱,值,說明。

發佈:此方法通過完整的表單傳輸信息。您無法在地址欄中看到詳細說明。當頁面顯示時。

-1
NSString *myUrlString =[NSString stringWithFormat: @"your url]; 
NSString *postdata=[NSString stringWithFormat:@"emailId=%@&password=%@,username,password]; 
NSLog(@"%@",postdata); 

//create a NSURL object from the string data 
NSURL *myUrl = [NSURL URLWithString:myUrlString]; 

//create a mutable HTTP request 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl]; 
//sets the receiver’s timeout interval, in seconds 
[urlRequest setTimeoutInterval:30.0f]; 
//sets the receiver’s HTTP request method 
[urlRequest setHTTPMethod:@"POST"]; 
//sets the request body of the receiver to the specified data. 
[urlRequest setHTTPBody:[postdata dataUsingEncoding:NSUTF8StringEncoding]]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
//Loads the data for a URL request and executes a handler block on an 
//operation queue when the request completes or fails. 
[NSURLConnection 
sendAsynchronousRequest:urlRequest 
queue:queue 
completionHandler:^(NSURLResponse *response, 
        NSData *data, 
        NSError *error) { 
    if ([data length] >0 && error == nil){ 
     //process the JSON response 
     //use the main queue so that we can interact with the screen 
     dispatch_sync(dispatch_get_main_queue(), ^{ 
      [self parseResponse:data]; 
     }); 
    } 
    else if ([data length] == 0 && error == nil){ 
     NSLog(@"Empty Response, not sure why?"); 
    } 
    else if (error != nil){ 
     NSLog(@"Not again, what is the error = %@", error); 
    } 
}]; 
} 

- (void) parseResponse:(NSData *) data 
{ 
    responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"JSON = %@", responseData); 
    NSLog(@"Response ==> %@", responseData; 

最後,你從那個特定的網址得到了迴應,並且你想要它自己的方式。