【问题标题】:objective-c use SBjson read file.json in project but NSArray return nullobjective-c 在项目中使用 SBjson 读取 file.json 但 NSArray 返回 null
【发布时间】:2012-12-18 15:46:46
【问题描述】:

th.json

{"lessons":[{"id":"38","fach":"D"},{"id":"39","fach":"M"}]}

ViewController.m

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *JsonData = [bundle pathForResource:@"th" ofType:@"json"];

SBJsonParser *parser = [[SBJsonParser alloc] init] ;

NSDictionary *jsonObject = [parser objectWithString:JsonData error:NULL];

NSArray *list = [jsonObject objectForKey:@"lessons"];

NSLog(@"%@", list);

输出NSLog列表返回

(null)

我的应用程序在我的项目内部使用 json 文件。 和我的项目文件夹中的“th.json”。 但是 NSArray *list 无法在 Json 文件中显示数据。

【问题讨论】:

    标签: json null nsarray internal sbjson


    【解决方案1】:

    您需要将文件的内容提供给SBJsonParser。您的代码只是将文件的 path 提供给解析器。试试这个:

    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [bundle pathForResource:@"th" ofType:@"json"];
    NSLog(@"Path: %@", path);
    
    NSData *jsonData = [NSData dataWithContentsOfFile:path];
    NSLog(@"Data: %@", jsonData);
    
    SBJsonParser *parser = [[SBJsonParser alloc] init] ;
    
    NSDictionary *jsonObject = [parser objectWithData:jsonData];
    NSLog(@"%@", jsonObject);
    
    NSArray *list = [jsonObject objectForKey:@"lessons"];
    NSLog(@"%@", list);
    

    【讨论】:

    • 为什么构建错误:'SBJson4Parser' 没有可见的@interface 声明选择器'objectWithData:'
    • SBJson4Parser 来自 SBJson 版本 4 及更高版本,SBJsonParser(在此示例中使用)在 SBJson 版本中小于 4。这是一个主要版本更改,因为 API发生了显着变化。因此,一切都被重命名了,因此您可以在同一个应用程序中同时使用版本 3 和 4。
    【解决方案2】:
    for (NSDictionary *dataDict in myitems) {
            NSString *itemName = [dataDict objectForKey:@"itemName"];
            NSLog(@"itemName = %@",itemName);
        }    
    

    插入字符串使其工作。

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      相关资源
      最近更新 更多