使用AFNetworking未正确反序列化字典中的JSON编码字典


JSON encoded dictionary in a dictionary not correctly deserialised using AFNetworking

在我的PHP后端,我返回一个JSON如下:

            $results_array=array();
            $stmt->bind_result($IdUser,$username);
            while($stmt->fetch()) {
                $row = array();
                $row["IdUser"]=$IdUser;
                $row["username"]=$username;
                $results_array[]=$row;
            }
            $stmt->close();
            echo json_encode(array("Response"=>"Login okay", "code"=>200, "results"=>$results_array));

我的AFHTTPRequestOperation管理器返回responseObject(命名结果)。

现在我想获得用户:

NSDictionary *user = (NSDictionary *)[results objectForKey:@"results"];
NSLog(@"%@",user);
[[API sharedInstance] setUser:user];
[self.navigationController popViewControllerAnimated:YES];
[self showAlertWithTitle:@"Logged in" andMessage:[NSString stringWithFormat:@"Welcome %@",[user objectForKey:@"username"]]];

应用程序崩溃与"NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance"。我正在使用NSLog检查"user"对象,我得到:

{IdUser = 49;用户名= kenny;}

仍然是JSON格式。我哪里做错了?为什么它不反序列化到NSDictionary中的NSDictionary?

您有一个类型为"User"的项数组,并且"results"包含一个字典数组,而不是简单的字典。试试下面的代码:

NSArray *userList = results[@"results"];
NSDictionary *user = userList.firstObject;