Ios 使用JSON数据加载UIPickerView(带嵌套数组)
JSON数据如下所示,其中sites数组中的每个对象都有自己的数组,称为categories,如下所示:Ios 使用JSON数据加载UIPickerView(带嵌套数组),ios,arrays,json,uipickerview,multidimensional-array,Ios,Arrays,Json,Uipickerview,Multidimensional Array,JSON数据如下所示,其中sites数组中的每个对象都有自己的数组,称为categories,如下所示: "sites": [ { "nid": "25109", "name": "guard.com", "url": "http:\/\/www.trial.com\/guard\/", "description": null, "categories": [ "Sports", "Security", "Product" ] }, {
"sites": [
{
"nid": "25109",
"name": "guard.com",
"url": "http:\/\/www.trial.com\/guard\/",
"description": null,
"categories": [
"Sports",
"Security",
"Product"
]
},
{
"nid": "29402",
"name": "paint.com",
"url": "http:\/\/www.trial.com\/paint\/",
"description": null,
"categories": [
"Sales",
"Fashion",
"Design"
]
},
我添加了一个UIPickerView作为我的应用程序的过滤器。
我需要加载一个包含JSON数据中所有类别的UIPickerView。如何仅解析来自categories数组的数据
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//1
#define kLatestKivaLoansURL [NSURL URLWithString:@"file:///Users/vishnup/Documents/document.json"]
//2
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* Details = [json objectForKey:@"catogeries"]; //2
// 1) Get the latest loan
NSDictionary* yourValues = [Details objectAtIndex:0];
然后将值中的内容传递给pickerview。您可以获得如下类别:
NSDictionary* responseDictionary = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *categories = responseDictionary[@"sites"][@"categories"];
我只是简单地将objectForKey更改为valueForKey,它就成功了!!在categories数组中没有任何对象,只有字符串或值,这是非常合理的
谢谢你们的帮助 可以在这里添加实际的JSON吗。这看起来像是序列化到NSDictionary。刚刚添加了原始JSON。。。我用这个例子来解析json数据。简单而有用one@vishnuvarthan伟大的参考!本教程非常精彩!:NSArray*values=[yourValues-allValues];self.pickerview=值//pickerview是您的选择器视图名称。试试这个就试试吧。它还是空着的。我尝试访问的数组是否是字符串数组?。。