【问题标题】:Parse json_encoded data into an array to be used for a UIPickerView - Xcode将 json_encoded 数据解析为用于 UIPickerView 的数组 - Xcode
【发布时间】:2012-10-11 18:20:46
【问题描述】:

我希望填充一个数组以在选取器视图中使用。数组的数据是从数据库表中生成的。

我有以下 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 连接到 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数组。

提前谢谢...

【问题讨论】:

  • 如何将 PHP 生成的 JSON 导入 iOS 应用程序?能否提供更多代码?

标签: iphone objective-c xcode uipickerview json


【解决方案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

【讨论】:

  • 我需要添加代码来遍历数组吗?我更新了我的代码,这会改变你的方法吗?
  • 我会放入你的对象作为你的结果键。创建第二个 serviceResults 数组可能更容易;看起来应该给你一个数据数组。对于该数组中的每个项目,我将创建一个字典并将 quivername 键的对象 (NSString*) 存储到数组 serviceResults 中,然后它应该为您提供一个字符串数组。
  • 好的,所以我添加了这段代码。我应该用任何东西替换“yourkey”吗?另外,我如何调用该函数?假设在 ViewDidLoad 中添加: NSMutableArray* myData = [self fetchedData:responseData];但是,当我这样做时,我收到一个错误“使用未声明的标识符'responseData'...
  • 所以,我只需要执行以下操作:用您的代码替换“//success, parse json data into array for UIPickerview”以遍历数组。其他一切都是不必要的。因此,鉴于该代码,我将其标记为正确...
【解决方案2】:

你可以试试这个(未经测试):

  //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...

【讨论】:

  • 我只是更新代码以显示它是如何进入 iphone 的,这会改变你描述的方法吗?
  • 不,该方法只需要json并对其进行转换,json如何进入并不重要......
  • 假设在 ViewDidLoad 添加:NSMutableArray* myData = [self fetchedData:responseData];但是,当我这样做时,我收到一个错误“使用未声明的标识符'responseData'...
  • 方法是找你传NSData,不是NSMutableArray
猜你喜欢
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多