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

时间:2012-06-02 22:26:08

标签: ios json nsdictionary

我正在尝试将数据从我的JSON文件传递到简单的ViewController,但我不知道在哪里实际传递该数据。我是否可以添加到setDataToJson方法中,还是会在viewDidLoad方法中添加数据?

这是我的代码

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

2 个答案:

答案 0 :(得分:40)

问题在于您尝试检索文件的方式。为了做到正确,你应该首先在捆绑中找到它的路径。尝试这样的事情:

+(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来设置标签:

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

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

答案 1 :(得分:1)

应该是valueForKey

示例:

name.text = [infomation valueForKey:@"AnimalName"];