【问题标题】:Load UIPickerView with JSON Data (w/nested array)使用 JSON 数据加载 UIPickerView(带嵌套数组)
【发布时间】:2014-08-11 06:36:46
【问题描述】:

JSON 数据是这样读取的,其中站点数组中的每个对象都有自己的数组,称为“类别”:

"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。如何仅解析类别数组中的数据?

【问题讨论】:

  • 你能在这里添加实际的 JSON。这似乎序列化为 NSDictionary。
  • 刚刚添加了原始 JSON..
  • raywenderlich.com/5492/working-with-json-in-ios-5。我用这个例子来解析 json 数据。简单而有用的一个
  • @vishnuvarthan 很好的参考!这个教程太棒了! :)

标签: ios arrays json uipickerview multidimensional-array


【解决方案1】:
#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 中的内容传递给您的pickerview。

【讨论】:

  • NSArray * values = [yourValues allValues]; self.pickerview=值; //pickerview 是您的选择器视图名称。试试这个
  • 刚试过。它仍然显示为空。我尝试访问的数组是否是字符串数组?..
【解决方案2】:

您可以像这样获取类别:

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

【讨论】:

    【解决方案3】:

    我只是将我的 objectForKey 更改为 valueForKey,它起作用了!!在 category 数组中实际上没有对象,只有字符串或值,这是完全有道理的。

    感谢大家的帮助! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2014-02-15
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多