简体   繁体   English

在为iPhone解析json时获取null?

[英]Getting null while parsing json for iphone?

I am trying to Parse JSON here and perform some action. 我试图在这里解析JSON并执行一些操作。 I am getting response in a string as given below why json is returning null, 我在如下所示的字符串中获取响应,为什么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);

I am getting response here... 我在这里得到回应...

Response ==> {"success":1}{"tag":"login","success":1,"error":0} 响应==> {“成功”:1} {“标签”:“登录”,“成功”:1,“错误”:0}

If response can come in string why it is not coming to below code? 如果响应可以字符串形式出现,为什么它不出现在下面的代码中? Can we get the success function/variable or pass the string to jsonData in below code... 我们能否获取成功函数/变量或将字符串传递给以下代码中的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!"];
        }

Everytime I run this it executes the else block... 每当我运行它时,它就会执行else块...

When I try to parse Json It is retuning me null value 当我尝试解析Json时,我将其调整为空值

2013-12-18 07:52:09.193 ColorPicker[15867:c07] json data is (null) 2013-12-18 07:52:09.193 ColorPicker[15867:c07] 0 2013-12-18 07:52:09.193 ColorPicker [15867:c07] json数据为(空)2013-12-18 07:52:09.193 ColorPicker [15867:c07] 0

I am sending response from json over here 我在这里从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);
       }
   }

I have almost same web service for registration with register tag, and it is working fine with same code :O 我使用注册标签几乎可以使用相同的Web服务进行注册,并且使用相同的代码也可以正常使用:O

If you jsonData is nil. 如果您的jsonData为nil。 Try to parse in this way 尝试以这种方式解析

You response should be this if it is array: 如果是数组,您的响应应该是这样:

Response : [{"success":1},{"tag":"login","success":1,"error":0}]

If dictionary then response should be 如果是字典,则响应应为

Response : {"tag":"login","success":1,"error":0}

And Replace this 并替换这个

    NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];


    NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];

With

    NSInteger success = [[jsonData objectForKey:@"success"] integerValue];

OR 要么

    NSInteger success = [[jsonData valueForKey:@"success"] integerValue];

OR 要么

    NSInteger success = [jsonData[@"success"] integerValue];

This response: 这个回应:

Response ==> {"success":1}{"tag":"login","success":1,"error":0} 响应==> {“成功”:1} {“标签”:“登录”,“成功”:1,“错误”:0}

seems to have two valid json strings: 似乎有两个有效的json字符串:

  • {"success":1} and {“成功”:1}并且
  • {"tag":"login","success":1,"error":0} { “标记”: “登录”, “成功”:1, “错误”:0}

So, your php code is probably writing out json at two places. 因此,您的php代码可能在两个地方写出了json。 Debugging the script, eg, by putting different values for success(the common key in the two json strings), should help to nail it down. 例如,通过放置不同的成功值(两个json字符串中的公共键)来调试脚本,应该有助于确定该脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM