【发布时间】:2013-12-18 14:41:25
【问题描述】:
我正在尝试在这里解析 JSON 并执行一些操作。我在字符串中得到响应,如下所示,为什么 json 返回 null,
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
我正在这里收到回复...
响应 ==> {"success":1}{"tag":"login","success":1,"error":0}
如果响应可以以字符串形式出现,为什么它不会出现在下面的代码中?我们可以在下面的代码中获取成功函数/变量或将字符串传递给jsonData...
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"json data is %@",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
NSLog(@"%d",success);
if(success == 1)
{
NSLog(@"Login SUCCESS");
[self alertStatus:@"Logged in Successfully." :@"Login Success!"];
ColorPickerViewController *cpvc =[[ColorPickerViewController alloc] init];
[self.navigationController pushViewController:cpvc animated:YES];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
[self alertStatus:error_msg :@"Login Failed!"];
}
每次我运行它都会执行 else 块...
当我尝试解析 Json 时,它正在重新调整我的空值
2013-12-18 07:52:09.193 ColorPicker[15867:c07] json 数据为 (null) 2013-12-18 07:52:09.193 ColorPicker[15867:c07] 0
我在这里发送来自 json 的响应
// Get tag
$tag = $_POST['tag'];
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
我有几乎相同的 web 服务用于注册标签注册,并且使用相同的代码可以正常工作:O
【问题讨论】:
-
在
JSONObjectWithData:方法中传递NSError并打印错误并找出它返回null的原因 -
我认为这不是一个有效的 json
-
@MidhunMP 正是我现在认为的。我也不认为它是一个有效的 json。
-
@Quick App 我认为您可以将该 urlData 作为字符串分配给 NSDictionary 并获取键“成功”的值并使用它。
标签: php ios json web-services nsjsonserialization