0

PHP Web サービスから送信された iOS の配列からデータを取得したいと考えています。配列の構造は次のとおりです。

[
    {
        "fullname": "Kate Bell",
        "email": "kate-bell@mac.com"
    },
    {
        "fullname": "Kate Bell",
        "email": "www.creative-consulting-inc.com"
    },
    {
        "fullname": "Daniel Higgins",
        "email": "d-higgins@mac.com"
    },
    {
        "fullname": "John Appleseed",
        "email": "John-Appleseed@mac.com"
    }
]

注: 配列の長さは任意です。

PHP コード:

mysql_select_db("mydb");

    $ReturningArray = array();

    foreach($Contacts_Array as $arr)
    {
        foreach($arr['emails'] as $email_address)
        {
            $query = "select email from table where email='".$email_address."'";
            $result = mysql_query($query);

            $row = mysql_fetch_assoc($result);

            if(empty($row))
            {
                $Contact = array(
                "fullname" => $arr['fullname'],
                 "email"   => $email_address
                 );

                $ReturningArray[] =  $Contact;
            }
        }

    }

    echo json_encode($ReturningArray);

アップデート:

このコードを試しましたが、うまくいきません

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        // NSString *Result = [[NSString alloc] initWithData:data      encoding:NSUTF8StringEncoding];
   // NSLog(@"Result in NonTroopeUsers : %@",Result);

        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        NSLog(@"COUNT :%d",[array count]);

        for (NSDictionary* item in array)
        {
            NSString *fullname = [item objectForKey:@"fullname"];
            NSString *email = [item objectForKey:@"email"];

            NSLog(@"Full name: %@",fullname);

            NSLog(@"email: %@",email);
        }

    }

配列カウントはゼロですが、コメント付きのコードは nslog で受信したデータを示しています。

4

3 に答える 3

0

connection: didReceiveData:メソッド内で変換を実行しないでください。部分的なデータしかない場合があります。そして、これはデータのチャンクを与えるために何度も呼び出される可能性があります。完全なデータを取得するには、これらの部分データのチャンクを追加する必要があります。

JSON の解析には NSJSONSerialization を使用できます。

NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

また、

メンバー変数を作成する

 NSMutableData *netData;

以下のメソッドを実装します

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
     if(netData == nil)
          netData = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [netData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
      //// Here convert the Full Data to JSON, 
     NSArray *array = [NSJSONSerialization JSONObjectWithData:netData options:kNilOptions error:nil];
     NSLog(@"%@",array);


}
于 2013-06-12T07:20:55.587 に答える