【问题标题】:How to parse Nested JSON from URL?如何从 URL 解析嵌套的 JSON?
【发布时间】:2015-05-08 17:36:51
【问题描述】:

试图解析嵌套的 json。试图抓取嵌套 json 文件中的内容。似乎是一个字典数组。在其中,我们想要一个包含字典内容(帖子)的字段。然后在 custom_fields 中,它是一个数组的数组。

///////////// ViewController.h //////////
@property (nonatomic, strong) NSMutableArray *jsonArray;     
@property (nonatomic, strong) NSMutableArray *postArray;   
@property (nonatomic, strong) NSMutableDictionary *fieldArray;   
@property (nonatomic, strong) NSMutableArray *testArray;   

- (void) retrieveData;

@end




/////////////////  ViewController.m   //////////////////

#import "ViewController.h"
#import "Model.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize jsonArray, postArray, fieldArray, testArray;

- (void)viewDidLoad {
    [super viewDidLoad];

    //Set title of VC
    self.title = @"SF";

    //Load data
    [self retrieveData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:     (NSInteger)section {
    // Return the number of rows in the section.
    return fieldArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView   dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    //Configure cell:  
    Model * modelObject = [[Model alloc] init];
    modelObject = [fieldArray objectAtIndex:indexPath.row];
    cell.tag = indexPath.row;
    cell.textLabel.text = modelObject.address;
    NSLog(@"the text is %@", modelObject.address);

    //Accessory
    cell.accessoryType = UITableViewCellAccessoryNone; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    return cell;
}

- (void) retrieveData
{
    NSURL * url = [NSURL URLWithString:getDataURL];
    NSData * data = [NSData dataWithContentsOfURL:url];

    jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    //Set up arrays
    postArray = [[NSMutableArray alloc] init]; 
    fieldArray = [[NSMutableDictionary alloc] init];
    testArray = [[NSMutableArray alloc] init];

    NSLog(@"old post class: %@", NSStringFromClass([postArray class]));
    NSLog(@"old field class: %@", NSStringFromClass([fieldArray class]));
    NSLog(@"old test class: %@", NSStringFromClass([testArray class]));

    //Set up array from jsonArray
    postArray = [jsonArray valueForKey:@"posts"];
    fieldArray = [postArray valueForKey:@"custom_fields"];

    NSLog(@"new post class: %@", NSStringFromClass([postArray class]));
    NSLog(@"new field class: %@", NSStringFromClass([fieldArray class]));
    NSLog(@"new test class: %@", NSStringFromClass([testArray class]));

    NSLog(@"Test Array: %@", fieldArray);

    //Set up json array
    for (int i = 0; i < fieldArray.count; i++)
    {
        //Create object
        NSString * name = [[fieldArray valueForKey:@"cf_name"] objectAtIndex:i];
        //NSLog(@"name: %@", name);

        NSString * address = [[fieldArray valueForKey:@"cf_Address"] objectAtIndex:i];
        //NSLog(@"address: %@", address);

        NSString * contact = [[fieldArray valueForKey:@"cf_contact"] objectAtIndex:i];
        //NSLog(@"contact: %@", contact);
    }

    //Reload table view
    [self.tableView reloadData];
}

@end

【问题讨论】:

  • 如果你的数据链接是可信的,那么最外层的 JSON 结构是一个对象,而不是一个数组。此外,它不是可变的,因为您没有为此指定解析选项。然而,“posts”的内容一个数组,在它上面使用valueForKey会返回一个“custom_fields”值的数组,其中每个单独的值都是一个NSDictionary。为“custom_fields”数组的第 n 个条目请求“cf_Business_name”元素将返回一个 NSArray,通常包含一个名称。也就是说,您认为 NSString 是 NSArray,正如异常清楚地告诉您的那样。
  • 你真的需要收拾这个烂摊子,区分哪些是数组,哪些是字典。使用valueForKey 及其亲属与以更传统的方式剥离 JSON 相比,您会造成很多浪费的动作(和混乱)。
  • 如果你查看过异常堆栈跟踪,它会告诉你错误的确切位置。
  • 看来 custom_fields 中的值是数组(例如 cf_Business_Name、cf_Address....)。 json的结构是:

标签: ios json uitableview datamodel


【解决方案1】:

问题与错误描述的完全一样。您试图在NSArray 上调用isEqualToString:,这会导致崩溃。我不确定你到底在哪里进行比较,但它正在发生。这可能是由于您在解析 JSON 时使用的是 valueForKey: 而不是 objectForKey:

【讨论】:

  • 我之前尝试过 objectForKey,但这给了我一个“objectForKey 可能不适用于 postArray”和“objectForKey 可能不适用于 fieldArray”。我
  • 使用valueForKey 将在用于字典数组时返回一个数组(在上面的大多数使用中都是这种情况)。如果您了解它,这是一个有用的功能,但如果您不了解,则会非常混乱。
【解决方案2】:

这很棘手。我要感谢 Hot Licks!

JSONData 上的 postVal = valueForKey 将输出转换为数组。

比我遍历字典数组如下

for (NSMutableDictionary *postDict in postVal) {}

其中我想要字典中的一个字段。所以我使用了以下内容:

id key;
while((key = [enumerator nextObject])) {}

之后,所有键都是字符串,但值是数组。 要将数组作为字符串获取,我使用了以下

NSString * bName = [fieldVal objectForKey:key][0];

类型终于是NSString了!!!!!!

谢谢。

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多