Passing data from local file using json

后端 未结 2 602
一向
一向 2021-02-02 14:20

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 set

相关标签:
2条回答
  • 2021-02-02 14:35

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

    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];
    }
    
    0 讨论(0)
  • 2021-02-02 14:35

    It should be valueForKey instead.

    Example:

    name.text = [infomation valueForKey:@"AnimalName"];
    
    0 讨论(0)
提交回复
热议问题