首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用json从本地文件传递数据

使用json从本地文件传递数据
EN

Stack Overflow用户
提问于 2012-06-03 06:26:08
回答 2查看 20.5K关注 0票数 17

我试图将数据从我的JSON文件传递到一个简单的ViewController上,但我不知道将数据真正传递到哪里。我只能添加到我的setDataToJson方法中,还是应该将数据添加到我的viewDidLoad方法中?

以下是我的代码

代码语言:javascript
复制
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation;
@end

@implementation NSDictionary(JSONCategories)

+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation{
    NSData* data = [NSData dataWithContentsOfFile:fileLocation];
    __autoreleasing NSError* error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data 
                                                options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}
@end

@implementation ViewController
@synthesize name;

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)setDataToJson{

    NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
    name.text = [infomation objectForKey:@"AnimalName"];//does not pass data
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-03 16:40:46

问题在于您尝试检索文件的方式。为了正确地完成它,你应该首先在包中找到它的路径。尝试如下所示:

代码语言:javascript
复制
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:[fileLocation stringByDeletingPathExtension] ofType:[fileLocation pathExtension]];
    NSData* data = [NSData dataWithContentsOfFile:filePath];
    __autoreleasing NSError* error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data 
                                                options:kNilOptions error:&error];
    // Be careful here. You add this as a category to NSDictionary
    // but you get an id back, which means that result
    // might be an NSArray as well!
    if (error != nil) return nil;
    return result;
}

这样做之后,一旦加载了视图,就应该能够通过检索json来设置标签,如下所示:

代码语言:javascript
复制
-(void)setDataToJson{
    NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
    self.name.text = [infomation objectForKey:@"AnimalName"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setDataToJson];
}
票数 40
EN

Stack Overflow用户

发布于 2012-06-03 13:02:28

它应该是valueForKey

示例:

代码语言:javascript
复制
name.text = [infomation valueForKey:@"AnimalName"];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10866403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档