Search code examples
iphoneobjective-cxcodeuipickerviewjson

Parse json_encoded data into an array to be used for a UIPickerView - Xcode


I'm looking to populate an array to be used in a pickerview. The data for the array is generated from a database table.

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"}
 ]
}

UPDATE FOR WEBSERVICE PHP CODE

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');
}
}

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
        }

        }];
}

I need the following:

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];

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.

Thanks in advance...


Solution

  • 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;
    }
    

    EDIT: For more info check out this explanation for JSON parsing http://www.raywenderlich.com/5492/working-with-json-in-ios-5