0

我正在寻找一个要在pickerview中使用的数组。数组的数据是从数据库表中生成的。

我有以下 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"}
 ]
}

WEBSERVICE PHP 代码更新

我将此功能作为网络服务运行:

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 服务/网站...

-(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)如何使用 quivername 值填充 NSMutable 数组?我试图让结果看起来像这样:

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

您应该能够使用 NSData 从返回 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;
 }

文德利希在这里解释...

于 2012-10-11T18:44:33.130 回答