简体   繁体   中英

Getting null while parsing json for iphone?

I am trying to Parse JSON here and perform some action. I am getting response in a string as given below why json is returning 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}

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

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

When I try to parse Json It is retuning me null value

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

I am sending response from json over here

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

If you jsonData is 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}

seems to have two valid json strings:

  • {"success":1} and
  • {"tag":"login","success":1,"error":0}

So, your php code is probably writing out json at two places. Debugging the script, eg, by putting different values for success(the common key in the two json strings), should help to nail it down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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