将json_encoded数据解析为一个数组,用于UIPickerView - Xcode

时间:2012-10-11 18:20:47

标签: iphone objective-c xcode uipickerview json

我希望填充一个数组,用于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代码

我将此功能作为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连接到WEBSERVICE /网站...

-(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数组。

提前致谢...

2 个答案:

答案 0 :(得分:1)

您应该能够从使用[NSData dataWithContentsOfURL:yourURLValue]返回JSON的URL获取NSData,然后根据您的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

的此解释

答案 1 :(得分: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 explains it here...