使用JSON数据加载UIPickerView(带嵌套数组)

时间:2014-08-11 06:36:47

标签: 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"
  ]

},

{
  "nid": "29402",
  "name": "paint.com",
  "url": "http:\/\/www.trial.com\/paint\/",
  "description": null,
  "categories": [
    "Sales",
    "Fashion",
    "Design"
  ]

},

我添加了UIPickerView作为我的应用的过滤器。 我需要加载UIPickerView以及JSON数据中的所有类别。如何仅从类别数组中解析数据?

3 个答案:

答案 0 :(得分:0)

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

然后将yourValues中的内容传递给您的选择视图。

答案 1 :(得分:0)

您可以获得以下类别:

NSDictionary* responseDictionary = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
NSArray *categories = responseDictionary[@"sites"][@"categories"];

答案 2 :(得分:0)

我只是将objectForKey更改为valueForKey,并且工作正常!完全合理的是,类别数组中几乎没有对象,只有字符串或值。

谢谢大家的帮助! :)