将json_encoded数据解析为用于UIPickerView的数组-Xcode [英] Parse json_encoded data into an array to be used for a UIPickerView - Xcode
问题描述
我正在寻找一个要在pickerview中使用的数组.数组的数据是从数据库表中生成的.
I'm looking to populate an array to be used in a pickerview. The data for the array is generated from a database table.
我有以下JSON_ENCODED数组(在php中创建):
I have the following JSON_ENCODED array (created in 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代码
UPDATE FOR WEBSERVICE PHP CODE
我将此功能作为Web服务运行:
I run this function as a webservice:
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服务/网站...
I USE THIS CODE IN XCODE TO CONNECT TO THE WEBSERVICE/WEBSITE USING NSNetworking...
-(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数组?我正在尝试使结果看起来像这样:
1) how can i populate an NSMutable array with the quivername value? I'm trying to get the result to look like this:
pickerArray1 = [[NSMutableArray alloc] initWithObjects:@"Kite Boarding",
@"Live and Die in LA", @"Bahamas Planning", @"My Trip to India", @"Snowboarding",
nil];
我假设我需要运行一个for循环,这将需要我首先计算"数组中的行数,但是我不确定.我不知道如何计算json_array中的行数或创建NSMutable数组.
I'm assuming I need to run a for loop which would require me to "count" the number of rows in the array first, but I'm not sure. I don't know how to count the number of rows in the json_array or create an NSMutable array.
预先感谢...
推荐答案
您应该能够使用[NSData dataWithContentsOfURL:yourURLValue]
从返回JSON的URL中获取NSData,然后使用类似于以下内容的方式传递数据并进行解析在您的JSON上:
You should be able to get your NSData from the URL that returns the JSON using [NSData dataWithContentsOfURL:yourURLValue]
, then pass the data and parse using something similar to what's below based on your 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
For more info check out this explanation for JSON parsing http://www.raywenderlich.com/5492/working-with-json-in-ios-5
这篇关于将json_encoded数据解析为用于UIPickerView的数组-Xcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!