1

In order to test the JSON handling of my app I have created a test.json file that I want to load into an UITableView in my UIViewController class. I have created the JSON file and made a separate json loading class (JSONLoader) that implements the code:

 #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

in the .h file, in the .m file I have:

 #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

Which I believe will work for both a JSON file loaded from a URL (the end goal) and also a JSON file I have in my Xcode project as a test. In the -viewDidLoad of my viewController.m file I use:

     //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];
                                                                    });

I import the JSONLoader file and also the class the represents a test JSON object (singular chatter) and in my implementation I declare a NSArray *_localChatters.

I'm pretty convinced this should work, however when I NSLog(...) the array it displays empty (), where it should have a list of class objects. This means the JSON is never being parsed by my JSONLoader in the first place.

Any particular reason this could happen?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    Don't complain until you fix this bug: `error:nil`. – Hot Licks Jul 11 '14 at 15:17
  • Thanks, I added error checking and I got it returns "the operation couldn't be completed". (Cocoa error 3840). I did some research [here](http://stackoverflow.com/questions/11594617/ios-json-deserialization-failure-stig-nsjsonserializer/11596858#11596858) however I still can't get my head around how I should fix this particular example. It can't recognize my test.json file? – canaanmckenzie Jul 11 '14 at 15:37
  • Which error are you checking, the one from NSURLConnection or the one from NSJSONSerialization? And have you printed out the JSON? (Convert NSData to NSString using UTF8 char set, then log the string.) – Hot Licks Jul 11 '14 at 15:39
  • Note that you did not quote the **entire** error message. What is the rest of it?? – Hot Licks Jul 11 '14 at 15:40
  • I added a NSError *error = nil; then for both of them I added &error and did a NSLog localizedDescription, it checks both. however I think from the error it is the NSURLConnection. As of right now the JSON is hardcoded into a test.json file that I wanted to access from the mainBundle, URLforResource: name withExtension: json, I've printed out the path, it seems to be correct so the code recognizes the file is there. – canaanmckenzie Jul 11 '14 at 15:49
  • also thats the only error that shows from the NSLog, "The operation couldn't be completed. (Cocoa error 3840.)" – canaanmckenzie Jul 11 '14 at 15:50
  • No, there is more to the message, if you NSLog it. Look at the question you linked above -- he got `2012-07-21 23:59:31.376 Whisper.Client.IOS[1058:fe03] Error : Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No string key for value in object around character 1.) UserInfo=0xc9632e0 {NSDebugDescription=No string key for value in object around character 1.}` – Hot Licks Jul 11 '14 at 16:01
  • (Don't log `localizedDescription`, just log the whole NSError object.) – Hot Licks Jul 11 '14 at 16:02
  • I see what you mean, here it is: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Badly formed object around character 492.) UserInfo=0xdc0d810 {NSDebugDescription=Badly formed object around character 492.} – canaanmckenzie Jul 11 '14 at 16:04
  • 1
    So you need to log the JSON string (as I described above) and figure out about where character 492 is. – Hot Licks Jul 11 '14 at 16:05
  • It was a comma that should have been there, thanks for everything @HotLicks, works great now. – canaanmckenzie Jul 11 '14 at 16:14
  • Don't forget that if you Google for "json parser" there are several online sites where you can paste a JSON string and have it syntax-checked and see it nicely formatted. – Hot Licks Jul 11 '14 at 16:18
  • Paste your JSON string into [jsonlint.com](http://jsonlint.com) – JeremyP Jul 11 '14 at 16:23

0 Answers0