文件中的JSON未加载到NSArray中

时间:2014-07-11 15:15:16

标签: ios objective-c json

为了测试我的应用的JSON处理,我创建了一个test.json文件,我想将其加载到UITableView类的UIViewController中。我创建了JSON文件并创建了一个单独的json加载类(JSONLoader)来实现代码:

 #import <Foundation/Foundation.h>

 @interface JSONLoader : NSObject

 //return an array of chat objects from the json file given by url
 - (NSArray *)chattersFromJSONFile:(NSURL *)url;

 @end

.h 文件中,在 .m 文件中我有:

 #import "JSONLoader.h"
 #import "Chatter.h"

 @implementation JSONLoader

 - (NSArray *)chattersFromJSONFile:(NSURL *)url {
 //create a NSURLRequest with the given URL
 NSURLRequest *request = [NSURLRequest requestWithURL:url
                                          cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                      timeoutInterval:30.0];
  //get data
  NSURLResponse *response;
  NSData *data = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:nil];

  //create NSDictionary from the JSON data
  NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

  //create new array to hold chatter information
  NSMutableArray *localChatters = [[NSMutableArray alloc] init];

  //get an Array of dictionaries with the key "chatters"
  NSArray *chatterArray = [jsonDictionary objectForKey:@"chatters"];

  //iterate through array of dictionaries
  for(NSDictionary *dict in chatterArray) {
    //create new chatter object for each one and initialize it with info from the  dictionary
    Chatter *chatter = [[Chatter alloc] initWithJSONDictionary:dict];
    //add the chatter to an array
    [localChatters addObject:chatter];
    }
    //return array
    return localChatters;
    }

    @end

我认为哪个版本适用于从JSON(最终目标)加载的URL文件以及我在 Xcode JSON文件>项目作为测试。在我的 viewController.m 文件的-viewDidLoad中,我使用:

     //create a new JSONLoader with a local file from URL
     JSONLoader *jsonLoader = [[JSONLoader alloc] init];
     NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"json"];
      NSLog(@"%@",url);

     //load the data on a background queue
     //use for when connecting a real URL
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                                                    _localChatters =     [jsonLoader chattersFromJSONFile:url];
                                                                     NSLog(@"%@",_localChatters);
                                                                    //push data on main thread (reload table view once JSON has arrived)
                                                                    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                                                                    });

我导入JSONLoader文件以及代表测试JSON对象的类(单数聊天),在我的实现中我声明了NSArray *_localChatters

我非常确信这应该有效,但是当我NSLog(...)数组时它显示为空(),它应该有一个类对象列表。这意味着JSON永远不会被我的JSONLoader解析。

这可能发生的任何特殊原因?

0 个答案:

没有答案