17

我试图将数据从我的 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
}
4

2 回答 2

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];
}
于 2012-06-03T08:40:46.037 回答
1

应该是valueForKey

例子:

name.text = [infomation valueForKey:@"AnimalName"];
于 2012-06-03T05:02:28.357 回答