0

我实现 JSON 解析如下:

-(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 和 Get 方法有什么区别?*

json解析还有其他方法吗?

4

5 回答 5

3

您正在使用在主线程上执行的同步请求,因此如果您需要在后台执行此操作,请使用异步加载。

POST METHOD: POST 方法生成一个 FORM 集合,作为 HTTP 请求正文发送。在表单中键入的所有值都将存储在 FORM 集合中。

GET 方法: GET 方法通过将信息附加到 URL(带有问号)来发送信息,并存储为 A Querystring 集合。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

于 2013-07-25T09:44:03.087 回答
1

您正在发出同步通信请求,这会减慢应用程序的速度。您应该发出异步请求以保持您的应用程序响应。它与解析 JSON 数据无关。

于 2013-07-25T09:43:04.340 回答
1

我建议AFNetworking在您的上下文中使用这将简化连接管理、后台队列执行和解析JSON您从服务器返回的内容。

下面的代码示例将创建一个HTTP带有 a 的客户端并从给定路径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
}];
于 2013-07-25T09:54:19.523 回答
0

Get:使用 get 方法,通过附加 url 的查询字符串发送值。因此,当页面在浏览器中显示时,您可以在地址栏上看到名称、值、描述。

Post:此方法通过完整的表格传输信息。您无法在地址栏上看到详细说明。页面显示时。

于 2014-11-05T05:25:41.853 回答
-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;

最后你从那个特定的 url 得到响应。你想要它做你自己的方式。

于 2015-03-13T11:05:55.470 回答