JSON NSURLConnection 返回的数据

JSON Data returned on NSURLConnection

我有一个 iOS 应用程序,用户在使用该应用程序之前必须注册。我在 Storyboard 中创建了 UI,并且正在从 UI 文本字段中读取用户详细信息。然后我将详细信息发送到 Register API,Register API 发回 JSON 响应。我正在使用 NSURLConnection 进行通信。

这是我从测试中收到的响应 URL - 仅用于测试目的: {"username":"Hans","password":"Hans"}

但是,当我尝试读取密码以确保该用户不存在时(同样,仅出于测试目的),我返回的密码值为 nil。

在我的 .h 文件中,我声明了数据和连接:

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

在我的 .m 文件中,当有人点击注册按钮时,我创建请求并启动连接,如下所示。我在示例中给出了一个虚拟 URL 但我收到的响应是: {"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];
    }
}

这里连接创建没有问题。

在我的 .m 文件中,我实现了委托方法,在 connectionDidFinishLoading() 中,我尝试读取返回的 JSON。下面是我为此使用的代码。

- (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

        });
    });
}

从下面的日志屏幕抓取中,您可以看到返回的 jsonString 有值,但 jsonArray 始终为 nil。错误内容为:error NSError * domain: @"NSCocoaErrorDomain" - code: 3840 0x00007ff158498be0

提前致谢。

您的 jsonString 实际上是 NSDictionary 对象 - 由 NSJSONSerialization 创建 - 您正在寻找,没有数组。在 JSON 字符串中,大括号 {} 表示字典,方括号 [] 表示数组

试试这个

- (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

    });
  });
}

编辑: 我忽略了 NSJSONSerialization 行末尾的 description 方法。那当然要删了。

您的代码有 2 个问题:

  1. 您正在将 JSON 服务器响应转换为 NSString。
  2. 您的 JSON 数据确实是一个 NSDictionary。

这必须解决您的问题:

- (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

    });
  });
}