0

ピッカービューで使用する配列を作成しようとしています。配列のデータは、データベーステーブルから生成されます。

次のJSON_ENCODED配列(phpで作成)があります:

{"result":
 [
  {"id":"3","quivername":"Kite Boarding"},
  {"id":"4","quivername":"Live and Die in LA"},
  {"id":"14","quivername":"Bahamas Planning"},
  {"id":"15","quivername":"My Trip to India"},
  {"id":"16","quivername":"Snowboarding"}
 ]
}

WEBSERVICEPHPコードの更新

この関数をWebサービスとして実行します。

passport($_SESSION['IdUser'])

function passport($userid) {

$result = query("SELECT id, quivername FROM quivers WHERE userid = $userid");

if (!$result['error']) {
    print json_encode($result);
} else {
        errorJson('Can not get passports');
    }
}

function query() {
global $link;
$debug = false;

//get the sql query
$args = func_get_args();
$sql = array_shift($args);

//secure the input
for ($i=0;$i<count($args);$i++) {
    $args[$i] = urldecode($args[$i]);
    $args[$i] = mysqli_real_escape_string($link, $args[$i]);
}

//build the final query
$sql = vsprintf($sql, $args);

if ($debug) print $sql;

//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {

    $rows = array();

    if ($result!==true)
    while ($d = mysqli_fetch_assoc($result)) {
        array_push($rows,$d);
    }

    //return json
    return array('result'=>$rows);

} else {

    //error
    return array('error'=>'Database error');
}
}

XCODEでこのコードを使用して、NSNetworkingを使用してWebサービス/Webサイトに接続します...

-(void)getPassports {
    //just call the "passport" command from the web API
    [[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"passport",@"command",
        nil]
        onCompletion:^(NSDictionary *json) 
        {
        //got passports, now need to populate pickerArray1
        if (![json objectForKey:@"error"])
        {
                    //success, parse json data into array for UIPickerview
        } 
        else
        //error, no passports
        {
                    // error alert
        }

        }];
}

私は以下が必要です:

1)NSMutable配列にquivername値を入力するにはどうすればよいですか?私は次のような結果を得ようとしています:

pickerArray1 = [[NSMutableArray alloc] initWithObjects:@"Kite Boarding",
@"Live and Die in LA", @"Bahamas Planning", @"My Trip to India", @"Snowboarding",
nil];

最初に配列の行数を「カウント」する必要があるforループを実行する必要があると想定していますが、よくわかりません。json_arrayの行数をカウントする方法や、NSMutable配列を作成する方法がわかりません。

前もって感謝します...

4

2 に答える 2

1

を使用してJSONを返すURLからNSDataを取得し[NSData dataWithContentsOfURL:yourURLValue]、データを渡して、JSONに基づいて以下のようなものを使用して解析できるはずです。

 //INVOKE WEB SERVICE QUERY IN VIEW DID LOAD -- RUNS ASYNC SO WONT BLOCK UI
- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL: 
          @"URLOFYOURWEBSERVICE"];  // <-- may need to cast string to NSURL....
        NSMutableArray *quivernames = [self performSelectorOnMainThread:@selector(fetchedData:) 
          withObject:data waitUntilDone:YES];
    });
}

- (NSMutableArray *)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    //ARRAY OR DICT DEPENDING ON YOUR DATA STRUCTURE
    NSDictionary* json = [NSJSONSerialization 
        JSONObjectWithData:responseData 

        options:kNilOptions 
        error:&error];
    //ITERATE AND/OR ADD OBJECTS TO YOUR NEW ARRAY
    NSMutableArray* JSONResultValues = [json objectForKey:@"yourKey"]; 
    NSMutableArray* resultValues = [[NSMutableArray alloc] init];
   for(int x = 0; x< [JSONResultValues count]; x++){
       NSDictionary *tempDictionary = [JSONResultValues objectAtIndex:x];
       [resultValues addObject:[tempDictionary objectForKey:@"quivername"]];
    }

    NSLog(@"Results Count: %@", [JSONResultValues count]);
   NSLog(@"Results Count: %@", [resultValues count]);
    return resultValues;
}

編集:詳細については、JSON解析のこの説明を確認してくださいhttp://www.raywenderlich.com/5492/working-with-json-in-ios-5

于 2012-10-11T18:35:59.860 に答える
0

あなたはこれを試すことができます(テストされていません):

  //convert this to NSData, not sure how it is getting into obj-c
 {"result":[
  {"id":"3","quivername":"Kite Boarding"},
  {"id":"4","quivername":"Live and Die in LA"},
  {"id":"14","quivername":"Bahamas Planning"},
  {"id":"15","quivername":"My Trip to India"},
  {"id":"16","quivername":"Snowboarding"}
]};

NSMutableArray* myData = [self fetchedData:responseData]; 

- (NSMutableArray* )fetchedData:(NSData *)responseData {

    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 

        JSONObjectWithData:responseData 

        options:kNilOptions 
        error:&error
    ];

    NSMutableArray* quivers = [json objectForKey:@"result"];

    return quivers;
 }

Wenderlichはここでそれを説明しています...

于 2012-10-11T18:44:33.130 に答える