Question

I can't believe I can't get even this simple test stub working with JSONKit...

I have a json file containing a valid JSON document, and this simple code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSError *err = nil;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dk" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&err];

    NSString *dkk = [[NSString alloc] initWithContentsOfFile:filePath];
    NSLog(@"Found file with contents: \n%@",dkk);

    if(jsonData)
    {
        NSLog(@"Data length is: %d",[jsonData length]);
        id objectReturnedFromJSON = [jsonData objectFromJSONData];
        if(objectReturnedFromJSON)
        {
            if([objectReturnedFromJSON isKindOfClass:[NSDictionary class]])
            {
                NSDictionary * dictionaryFromJSON = (NSDictionary *)objectReturnedFromJSON;
                // ...
            } else {
                NSLog( @"no dictionary from the data returned by the server... check the data to see if it's valid JSON");
            }
        } else {
            NSLog( @"nothing valid returned from the server...");
        }
    } else {
        NSLog( @"no data back from the server");
    }

}

The result of objectFromJSONData always seems to come back null. Output is shown below:

2013-01-15 00:58:37.187 JSONTest[38110:c07] Found file with contents: 
myObject = {
    "first": "John",
    "last": "Doe",
    "age": 39,
    "sex": "M",
    "salary": 70000,
    "registered": true,
    "favorites": {
        "color": "Blue",
        "sport": "Soccer",
        "food": "Spaghetti"
    } 
}

2013-01-15 00:58:51.818 JSONTest[38110:c07] Data length is: 196
2013-01-15 00:58:54.058 JSONTest[38110:c07] Data length is: (null)
(lldb) 

What the heck am I missing? The input JSON is valid (as shown by the NSLog statements).

Sorry if this is something stupid but I've wasted too much time even on this small test case, making me think I'm missing something.

Was it helpful?

Solution

The JSON you have is invalid. It doesn't have a root element, and also the myObject key isn't enclosed within parentheses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top