使用json从本地文件传递数据 [英] Passing data from local file using json

查看:438
本文介绍了使用json从本地文件传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从JSON文件传递到标签,并传递到一个简单的ViewController上,但是我不知道实际在哪里传递该数据.我能只添加到setDataToJson方法中还是将数据添加到我的viewDidLoad方法中?

I am trying to pass data to labels from my JSON file onto a simple ViewController but I don't know where to actually pass that data. Would I be able to just add to my setDataToJson method or would I add the data in my viewDidLoad method?

这是我的代码

@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
}

推荐答案

问题是您尝试检索文件的方式.为了正确执行此操作,您应该首先在捆绑软件中找到其路径.尝试这样的事情:

The problem is the way you're trying to retrieve your file. In order to do it right, you should find first its path in the bundle. Try something like this:

+(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来设置标签,如下所示:

After doing that and once your view is loaded, you should be able to set your labels by retrieving the json like this:

-(void)setDataToJson{
    NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
    self.name.text = [infomation objectForKey:@"AnimalName"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setDataToJson];
}

这篇关于使用json从本地文件传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆