JSON Data returned on NSURLConnection

I have an iOS app where Users have to Register before using the app. I have created the UI in Storyboard and I am reading the Users details from the UITextfields. I then send the details to the Register API that sends back a JSON response. I am using NSURLConnection for the communication.

Here is the response I am receiving from the test URL - for testing purposes only: {"username":"Hans","password":"Hans"}

However, when I try to read the password to make sure that the user doesn't already exists (again, just for testing purposes), I get nil returned for password value returned.

In my .h file I declare the Data and Connection:

@interface RegisterViewController : UIViewController <NSURLConnectionDataDelegate>
{
    // Conform to the NSURLConnectionDelegate protocol and declare an instance variable to hold the response data
    NSMutableData *buffer;
    NSURLConnection *myNSURLConnection;
}

In my .m file, when someone clicks the REGISTER button, I create the request and start the connection as below. I am giving a dummy URL in example but the response I am receiving is: {"username":"Hans","password":"Hans"}

- (IBAction)registerButtonClicked:(id)sender
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://myDummyURL/Login.php"]];

    // Construct the JSON Data
    NSDictionary *stringDataDictionary = @{@"firstname": firstname, @"lastname": lastname, @"email": email, @"password" : password, @"telephone" : telephone};
    NSError *error;
    NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:stringDataDictionary options:0 error:&error];

    // Specify that it will be a POST request
    [request setHTTPMethod:@"POST"];

    // Set header fields
    [request setValue:@"text/plain" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:requestBodyData];

    myNSURLConnection = [NSURLConnection connectionWithRequest:request delegate:self];

    // Ensure the connection was created
    if (myNSURLConnection)
    {
        // Initialize the buffer
        buffer = [NSMutableData data];

        // Start the request
        [myNSURLConnection start];
    }
}

The connection is created with no problem here.

In my .m file I implement the delegate methods and in connectionDidFinishLoading() I try and read the returned JSON. Below is the code I am using for this.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Dispatch off the main queue for JSON processing
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSError *error = nil;
        NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:buffer options:0 error:&error] description];

        // Dispatch back to the main queue for UI
        dispatch_async(dispatch_get_main_queue(), ^{

            // Check for a JSON error
            if (!error)
            {
                NSError *error = nil;
                NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
                NSDictionary *dictionary = [jsonArray objectAtIndex:0];
                NSString *test = [dictionary objectForKey:@"password"];
                NSLog(@"Test is: %@", test);
            }
            else
            {
                NSLog(@"JSON Error: %@", [error localizedDescription]);
            }

            // Stop animating the Progress HUD

        });
    });
}

From the log screen grab below you can see the jsonString returned has values but the jsonArray is always nil. The error reads: error NSError * domain: @"NSCocoaErrorDomain" - code: 3840 0x00007ff158498be0

在这里输入图像描述

Thanks in advance.


Your jsonString is in fact the NSDictionary object - created by NSJSONSerialization - you're looking for, there is no array. In a JSON string curly braces {} represent a dictionary and square brackets [] represent an array

Try this

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // Dispatch off the main queue for JSON processing
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&error];

    // Dispatch back to the main queue for UI
    dispatch_async(dispatch_get_main_queue(), ^{

        // Check for a JSON error
        if (!error)
        {
            NSString *test = [dictionary objectForKey:@"password"];
            NSLog(@"Test is: %@", test);
        }
        else
        {
            NSLog(@"JSON Error: %@", [error localizedDescription]);
        }

        // Stop animating the Progress HUD

    });
  });
}

Edit: I overlooked the description method at the end of the NSJSONSerialization line. Of course that must be deleted.


Your code has 2 issues:

  • You are converting JSON server response to NSString.
  • Your JSON data is indeed a NSDictionary.
  • This must fix your issue:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
      // Dispatch off the main queue for JSON processing
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&error];
    
        // Dispatch back to the main queue for UI
        dispatch_async(dispatch_get_main_queue(), ^{
    
            // Check for a JSON error
            if (!error)
            {
                NSString *test = [dictionary objectForKey:@"password"];
                NSLog(@"Test is: %@", test);
            }
            else
            {
                NSLog(@"JSON Error: %@", [error localizedDescription]);
            }
    
            // Stop animating the Progress HUD
    
        });
      });
    }
    
    链接地址: http://www.djcxy.com/p/30600.html

    上一篇: 任何通过Amazon SimpleDB实现MVCC的客户端库?

    下一篇: JSON数据在NSURLConnection上返回